Deitel & Associates, Inc. Logo

Back to
digg.png delicious.png blinkit.png furl.png
Internet & World Wide Web How to Program, 3/e
Internet & World Wide Web How to Program, 3/e

© 2004
pages: 1420

Amazon logo

This tutorial introduces CGI programming with Python's cgi module. The example we present uses the cgi module's escape function to encode operating system environment variables in XHTML format for display in a Web page. This tutorial is intended for students and developers who are already familiar with basic Python programming or who have read our prior Python tutorials (see the list at the bottom of this page).
Download the Code Examples
[Note: This tutorial is an excerpt (Section 35.6) of Chapter 35, Python, from our textbook Internet & World Wide Web How to Program, 3/e. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., INTERNET & WORLD WIDE WEB HOW TO PROGRAM, 3/E, 2004, pp.1261-1263. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]
35.6   CGI Programming
Python has many uses on the Web. Modules cgi (for access to XHTML forms), Cookie (to read and write cookies), smtplib (to manipulate SMTP messages), urllib (to manipulate Web data), ftplib (to perform client-side FTP tasks) and others provide powerful extensions that Web programmers can use to write CGI scripts quickly for almost any task. This section introduces Python CGI programming. We assume that the reader has installed and configured the Apache Web server. Apache does not usually need any special configuration to run a Python script; a script need merely be placed in the specified cgi-bin directory. XHTML documents should be placed in the server's document root directory. See Chapter 21 for more details.
Figure 35.16 gathers all the CGI environment variables and values and organizes them in an XHTML table that is displayed in a Web browser. Line 1
is a directive (sometimes called the pound-bang or shebang) that provides the server with the location of the Python executable. This directive must be the first line in a CGI script. For UNIX-based machines, this value might commonly be
#!/usr/bin/python or #!/usr/local/bin/python
depending on the actual location of the Python executable. [Note: If necessary, be sure to modify the shebang in each of the remaining chapter examples to reflect the actual location of Python on your system.]
Fig. 35.16 Displaying environment variables via CGI.
1   #!c:\Python\python.exe
2   # Fig 35.16:
3   # Program to display CGI environment variables
5   import os
6   import cgi
8   print "Content-type: text/html"
9   print
11   print """<!DOCTYPE html PUBLIC
12      "-//W3C//DTD XHTML 1.0 Transitional//EN"
13      "DTD/xhtml1-transitional.dtd">"""
15   print """
16   <html xmlns = "" xml:lang="en"
17      lang="en">
18      <head><title>Environment Variables</title></head>
19      <body><table style = "border: 0">"""
21   rowNumber = 0
23   for item in os.environ.keys():
24      rowNumber += 1
26      if rowNumber % 2 == 0:
27         backgroundColor = "white"
28      else:
29         backgroundColor = "lightgrey"
31      print """<tr style = "background-color: %s">
32      <td>%s</td><td>%s</td></tr>""" \
33         % ( backgroundColor, item,
34            cgi.escape( os.environ[ item ] ) )
36   print """</table></body></html>"""

Line 5 imports the os module that allows developers to access information about the operating system. We use the os module in this example to retrieve the system's environment variables. Line 6 imports the cgi module that provides functionalities for writing CGI scripts. In this example, we use the module to format output; in later examples, we use module cgi to perform more complex CGI tasks.
Lines 8-9 print a valid HTTP header. Browsers use HTTP headers to determine how to handle the incoming data, and a valid header must be sent to ensure that the browser displays the information correctly. The blank line below the header is required; without this line, the content will not be delivered properly to the client. Lines 11-13 print the XHTML DOCTYPE string to the browser.
The environ data member (line 23) of module os (imported in line 5) holds all the environment variables. This data member acts like a dictionary; therefore, we can access its keys via the keys method and its values via the [] operator. In lines 31-32, we print a new row in the table for each item returned by method os.environ.keys. This row contains the key and the key's value. Notice that we pass each environment variable to function cgi.escape. This function formats text in an "XHTML-safe" way-special XHTML characters such as < and & are formatted so that they appear in the document as they should. After we have printed all the environment variables, we close the table, body and html tags (line 36).

Additional Python Tutorials:

Introduction to Python
Python Basic Data Types, Control Statements and Functions

Tuples, Lists and Dictionaries

Python String Processing and Regular Expressions

Return to Tutorial Index