Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata