HTML file, this Python script resides on the same machine as the web server; it’s run
on the server machine to handle the inputs and generate a reply to the browser on the
client. It uses the cgi module to parse the form’s input and insert it into the HTML
reply stream, properly escaped. The cgi module gives us a dictionary-like interface to
form inputs sent by the browser, and the HTML code that this script prints winds up
rendering the next page on the client’s browser. In the CGI world, the standard output
stream is connected to the client through a socket.
Example 1-31. PP4E\Preview\cgi-bin\cgi101.py
#!/usr/bin/python
import cgi
form = cgi.FieldStorage() # parse form data
print('Content-type: text/html\n') # hdr plus blank line
print('
if not 'user' in form:
print('
Who are you?
')else:
print('
Hello %s!
' % cgi.escape(form['user'].value))And if all goes well, we receive the reply page shown in Figure 1-11—essentially, just
an echo of the data we entered in the input page. The page in this figure is produced
by the HTML printed by the Python CGI script running on the server. Along the way,
the user’s name was transferred from a client to a server and back again—potentially
across networks and miles. This isn’t much of a website, of course, but the basic prin-
ciples here apply, whether you’re just echoing inputs or doing full-blown e-whatever.
Figure 1-11. cgi101.py script reply page for input form
If you have trouble getting this interaction to run on Unix-like systems, you may need
to modify the path to your Python in the #! line at the top of the script file and make
it executable with a chmod command, but this is dependent on your web server (again,
more on the missing server piece in a moment).
54 | Chapter 1: A Sneak Preview