The cgi Module

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


import cgi
import os, urllib

ROOT = "samples"

# header
print "text/html"

query = os.environ.get("QUERY_STRING")
if not query:
 query = "."

script = os.environ.get("SCRIPT_NAME", "")
if not script:
 script = ""

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




<a href="">web</a>

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh © 2008-2020.
If you may any questions please contact us: