Writing a CGI Script
Credit: Luther Blissett
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.
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/html
<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)
}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 ...
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.
Read now
Unlock full access