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 dictDiscussion
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 ...