This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Trying to use matplotlib in a python CGI script naïvely will most likely result in the following error:

...
352, in _get_configdir
raise RuntimeError("'%s' is not a writable dir; you must set
environment variable HOME to be a writable dir "%h)
RuntimeError: '<WebServer DocumentRoot>' is not a writable dir; you must set
environment variable HOME to be a writable dir

Matplotlib needs the environment variable HOME to point to a writable directory. One way to accomplish this is to set this environment variable from within the CGI script on runtime (another way would be to modify the .htaccess file but that would be not as portable). The following template can be used for a cgi that uses matplotlib to create a png image:

   1 #!/usr/bin/python
   2 import os,sys
   3 import cgi
   4 import cgitb; cgitb.enable()
   5 
   6 # set HOME environment variable to a directory the httpd server can write to
   7 os.environ[ 'HOME' ] = '/tmp/'
   8 
   9 import matplotlib
  10 # chose a non-GUI backend
  11 matplotlib.use( 'Agg' )
  12 
  13 import pylab
  14 
  15 #Deals with inputing data into python from the html form
  16 form = cgi.FieldStorage()
  17 
  18 # construct your plot
  19 pylab.plot([1,2,3])
  20 
  21 print "Content-Type: image/png\n"
  22 
  23 # save the plot as a png and output directly to webserver
  24 pylab.savefig( sys.stdout, format='png' )

This image can then be accessed with a URL such as: http://localhost/showpng.py

As documented,some backends will not allow the output to be sent to sys.stdout. It is possible to replace the last line with the following to work around this:

   1 pylab.savefig( "tempfile.png", format='png' )
   2 import shutil
   3 shutil.copyfileobj(open("tempfile.png",'rb'), sys.stdout)

(Of course it is necessary to create and delete proper temp files to use this in production.)


CategoryCookbookMatplotlib

SciPy: Cookbook/Matplotlib/Using_MatPlotLib_in_a_CGI_script (last edited 2015-10-24 17:48:26 by anonymous)