Unix Power ToolsUnix Power ToolsSearch this book

42.8. cgi

Python provides the cgi module for writing CGI scripts. Much of the grunt work of writing a CGI script is in dealing with parsing the parameters handed to the script by the web server. The cgi module deals with all of those details and more.

NOTE: To use the cgi module, use import cgi rather than from cgi import*. The cgi module defines a lot of symbols (many for backwards compatibility) that you don't want polluting your namespace.

When you write a new script, consider adding the line:

import cgitb; cgitb.enable( )

This activates a special exception handler that will display detailed reports in the web browser if any errors occur. If you'd rather not show the guts of your program to users of your script, you can have the reports saved to files instead, with a line like this:

import cgitb; cgitb.enable(display=0, logdir="/tmp")

It's very helpful to use this feature during script development. The reports produced by cgitb provide information that can save you a lot of time tracking down bugs. You can always remove the cgitb line later when you have tested your script and are confident that it works correctly.

To get to information submitted to the CGI script, instantiate a FieldStorage object:

form = cgi.FieldStorage( )

The FieldStorage object acts much like a dictionary of CGI information; it implements the methods has_key( ) and keys( ) and can be accessed using the [ ] operator. For instance, the following code (which assumes that the Content-Type: header and blank line have already been printed) checks that the fields name and addr are both set to a non-empty string:

form = cgi.FieldStorage( )
if not (form.has_key("name") and form.has_key("addr")):
    print "<H1>Error</H1>"
    print "Please fill in the Name and Address fields."
    return
print "<p>Name: %s</p>" % form["name"].value
print "<p>Address: %s</p>" % form["addr"].value
...further form processing here...

The cgi module also supports ways to deal with multiple-selection form elements and uploaded files.

-- DJPH



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.