How to generate graphics dynamically on the web using Python CGI script?

John M. Gabriele john_sips_teaz at yahooz.com
Sun Jan 22 08:42:34 CET 2006


Luiz Geron wrote:
> I don't have experience on this, but I think that you can make the
> script return the image "contents" directly to the img tag, without
> passing it to a img file, so you can use something like this:
> 
> <img src="script_that_return_image_contents">
> 
> wich saves some processing and I/O.
> 

I like this method.

You have 2 cgi scripts: one that creates your html with that img
tag in it, and a 2nd one to generate the image file on the fly when
the browser asks for it.

For generating the plot, I tried pychart http://home.gna.org/pychart/
and it was pretty nice.

If using pychart, your script that emits image contents might look
like this:

------------------------ code ------------------------
#!/usr/bin/python

# Not using cgi module at this point, since this script
# isn't very smart yet. :)

import sys
sys.argv.append( '--format=png' )

print "Content-type: image/png"
print

from pychart import *
theme.get_options()
theme.scale_factor = 3
theme.reinitialize()

import random
data = []
for i in range(10):
     data.append( (i, random.random()* 3.0) )

xaxis = axis.X( format="/hL%d",  label="time" )
yaxis = axis.Y(  label="synaptic activity" )

ar = area.T( x_axis=xaxis, y_axis=yaxis, y_range=(0,None), size=(120,110) )
plot = line_plot.T( label="cortex data", data=data, ycol=1, tick_mark=tick_mark.star )
ar.add_plot( plot )
ar.draw()
--------------------- /code ------------------------

Try the script out -- it'll work as-is once you've installed pychart.

You can add logic to it to generate your plot depending on what
you pass in, encoded in the URL request. Just import the cgi
module for getting those parameters.

---J

-- 
(remove zeez if demunging email address)



More information about the Python-list mailing list