Using a Simple Dictionary for CGI Parameters

Credit: Richie Hindle

Problem

You want to lead a simpler life when writing simple CGI scripts, accessing form fields from a simple dictionary rather than from a cgi.FieldStorage instance.

Solution

The cgi module offers sophisticated functionality in its FieldStorage class, but for most web pages, you can access the form’s data as a normal dictionary. It’s not hard to build the dictionary from the FieldStorage object:

#!/usr/bin/python

import cgi

def cgiFieldStorageToDict(fieldStorage):
   """ Get a plain dictionary rather than the '.value' system used by the 
   cgi module's native fieldStorage class. """
   params = {}
   for key in fieldStorage.keys(  ):
      params[key] = fieldStorage[key].value
   return params

if _ _name_ _ == "_ _main_ _":
   dict = cgiFieldStorageToDict(cgi.FieldStorage(  ))
   print "Content-Type: text/plain"
   print
   print dict

Discussion

Rather than using Python’s cgi.FieldStorage class, a simple dictionary is enough for 90% of CGI scripts. This recipe shows you how to convert a FieldStorage object into a simple dictionary.

Install the above script into your cgi-bin directory as cgitest.py, then visit the script with some parameters. For example:

http://your-server/cgi-bin/cgitest.py?x=y

You should see a simple dictionary printed in response:

{'x': 'y'}

Note that the first line of the script must give the complete path to the Python interpreter with which you want to run your CGI script, so you may have to edit it, depending on your configuration and setup.

The FieldStorage system is necessary when your HTML form contains multiple fields with the same name, or when users upload large files to your script, but if all you have is a simple set of uniquely named controls, a plain dictionary is easier (and more Pythonic!) to work with. Since the point of the recipe is simplicity, we of course do not want to do anything complicated, such as subclassing FieldStorage or anything similar; getting a simple dictionary is the whole point, and this recipe is a simple way to satisfy this simple requirement.

See Also

Recipe 11.2 for a quick way to test your CGI setup; documentation of the standard library module cgi in the Library Reference; a basic introduction to the CGI protocol is available at http://hoohoo.ncsa.uiuc.edu/cgi/overview.html.

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.