I l@ve RuBoard Previous Section Next Section

11.3 Writing a CGI Script

Credit: Luther Blissett

11.3.1 Problem

You want to write a CGI script to process the contents of an HTML form. In particular, you want to access the form contents and produce valid output in return.

11.3.2 Solution

A CGI script is a server-side program that a web server launches to generate a web page dynamically based on remote client requests (typically, the user filled in an HTML form on his web browser and submitted it). The script receives its input information from the client through its standard input stream and its environment and generates HTTP headers and body on its standard output stream. Python's standard cgi module handles input tasks on the script's behalf, and your script directly generates output as needed:

#!/usr/bin/python

# Get the cgi module and the values of all fields in the form
import cgi
formStorage = cgi.FieldStorage(  )

# Get a parameter string from the form
theValue = formStorage['PARAM_NAME'].value

# Output an HTML document
outputTemplate = """Content-Type: text/plain

<html><head><title>%(title)s</title></head><body>
%(body)s
</body></html>
"""
print outputTemplate % {'title': "Howdy there!",
  'body': '<p>You typed: <tt>%s</tt></p>'%cgi.escape(theValue)
  }

11.3.3 Discussion

A CGI script needs to decode the input to a web page according to a well-defined format. This task is performed by Python's standard cgi module. You simply call cgi.FieldStorage and obtain a mapping from each name of a form's field to the field's contents. You can index it directly, as is done in this recipe. You can also use the get method to supply a default if a field is absent, and the keys method to get a list of keys. While this is all typical dictionary functionality, the mapping is not actually a dictionary (so it can handle repeated field names in a form and the cases in which the user is uploading large files), so you need to use the value attribute, as shown in the recipe, to actually get at each field's contents. See Recipe 11.4 for a simple way to turn a field storage object into a plain dictionary in cases in which you don't need the extra functionality it supplies.

To generate the resulting web page, you have many more choices, so the cgi module does not handle this part. Python embodies many other string-processing facilities to let you generate the strings you want to output, and you can simply use print statements to emit them once they're ready. What cgi does supply for this part of the task is a function, cgi.escape, which takes any string and escapes special characters it might contain. In other words, it turns each occurrence of the characters &, <, and > into the equivalent HTML entity, to ensure that the data you're emitting does not disturb the user's browser's ability to parse the actual HTML structure of your output document.

In this recipe, I use Python's % string format operator to generate the web page. I use it once with a mapping as the righthand side and with the named items title for the page's title and body for its body. I use it a second time to generate the body itself, in the simpler positional way that takes a tuple on the righthand side. When the tuple would have just one item (as it does here), you can also use just the item itself as further simplification, and this is what I do in the recipe.

11.3.4 See Also

Recipe 11.2 for a quick way to test your CGI setup; Recipe 11.4 for a simple way to turn a field storage object into a plain dictionary; 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.

    I l@ve RuBoard Previous Section Next Section