The cgi module provides a number of support functions and classes for CGI scripts. Among other things, it can parse CGI form data.
Example 7-40 shows a simple CGI script that returns a list of a files in a given directory (relative to the root directory specified in the script).
Example 7-40. Using the cgi Module
File: cgi-example-1.py import cgi import os, urllib ROOT = "samples" # header print "text/html" print query = os.environ.get("QUERY_STRING") if not query: query = "." script = os.environ.get("SCRIPT_NAME", "") if not script: script = "cgi-example-1.py" print "
" print "" print "file listing" print "" print "
" print "
" try: files = os.listdir(os.path.join(ROOT, query)) except os.error: files = [] for file in files: link = cgi.escape(file) if os.path.isdir(os.path.join(ROOT, query, file)): href = script + "?" + os.path.join(query, file) print "
<a href="%s">%s</a>" % (href, cgi.escape(link)) else: print "
%s" % link print "" print "" text/html
file listing
sample.gif
sample.gz
sample.netrc ...
sample.txt
sample.xml
sample~
<a href="cgi-example-1.py?web">web</a>
Core Modules
More Standard Modules
Threads and Processes
Data Representation
File Formats
Mail and News Message Processing
Network Protocols
Internationalization
Multimedia Modules
Data Storage
Tools and Utilities
Platform-Specific Modules
Implementation Support Modules
Other Modules