Testing Whether CGI Is Working
Credit: Jeff Bauer
Problem
You want a simple CGI program to use as a starting point for your own CGI programming or to test if your setup is functioning properly.
Solution
The cgi
module is normally used in Python CGI programming, but here we use
only its escape function to ensure that the value of an
environment variable doesn’t accidentally look to
the browser as HTML markup. We do all of the real work ourselves:
#!/usr/local/bin/python
print "Content-type: text/html"
print
print "<html><head><title>Situation snapshot</title></head><body><pre>"
import sys
sys.stderr = sys.stdout
import os
from cgi import escape
print "<strong>Python %s</strong>" % sys.version
keys = os.environ.keys( )
keys.sort( )
for k in keys:
print "%s\t%s" % (escape(k), escape(os.environ[k]))
print "</pre></body></html>"Discussion
The Common Gateway Interface (CGI) is a protocol that specifies how a web server runs a separate program (often known as a CGI script) that generates a web page dynamically. The protocol specifies how the server provides input and environment data to the script and how the script generates output in return. You can use any language to write your CGI scripts, and Python is well-suited for the task.
This recipe is a simple CGI program that displays the current version
of Python and the environment values. CGI programmers should always
have some simple code handy to drop into their
cgi-bin directories. You should run this script before wasting time slogging ...