Tuesday, August 23, 2011

Wednesday, August 17, 2011

pychart & web.py

I'm writing a web interface in web.py to display statistics on a migration of data that will take days to run. The migration will be done by several scripts which rsync on a loop to keep the data fresh and I expect that each run of the program will take less time than the previous run. The migration scripts are logging this and I want my web interface to display the shrinking synchronization window graphically. I used PyChart to create a graph within a web.py GET class and used PyChart's canvas and Python's StringIO to get web.py to display the image dynamically.
class pychart:
    def GET(self):
        # sample data, that will be passed as an argument (left for this demo)
        data = [(1, 6), # the first run took 6 days
                (2, 3), # the second run took 3 days
                (3, 1)] # the third run too
        import cStringIO
        from pychart import theme, axis, area, line_plot, line_style, tick_mark, canvas
        f = cStringIO.StringIO()
        can = canvas.init(f, format="png")
        theme.use_color = 1
        theme.scale_factor = 2
        theme.reinitialize()
        theme.get_options()
        xaxis = axis.X(format="/a-60/hL%d", tic_interval = 1, label="Runs")
        yaxis = axis.Y(tic_interval = 1, label="Days")
        ar = area.T(x_axis=xaxis, y_axis=yaxis, y_range=(0,None))
        plot = line_plot.T(label="Time to run", data=data,
                           line_style=line_style.red,
                           ycol=1, tick_mark=tick_mark.square)
        ar.add_plot(plot)
        ar.draw(can) 
        can.close()
        f.seek(0)
        web.header('Content-Type', 'image/png')
        return f