COMP249: CGI

Steve Cassidy

Server Side Scripting

The Common Gateway Interface

CGI Programs

Location of CGI Programs

Server Processing

When a server recieves a request for a CGI resource:

Example: Target Output

<html>
  <head>
    <title>Demo static HTML page</title>
  </head>
  <body>
    <h1>Hello COMP249!</h1>
  </body>
</html>

CGI Script in Python

#!/usr/local/bin/python
print "Content-type: text/html\n\n"
print "<html>"
print "<head>"
print "<title>Demo static HTML page</title>"
print "</head>"
print "<body>"
print "<h1>Hello COMP249!</h1>"
print "</body>"
print "</html>"
      

The first print statement is the Content-type line that specifies the media type of the output that is generated. This line is actually part of the HTTP response header sent back to the client.

This line is immediately followed by a blank line which must not contain any spaces or tabs (the '\n\n' bit). Remember the HTTP protocol.

CGI programs often fail since the programmer forgot the blank line.

After the blank line comes the HTML encoded text which is displayed on the user's browser.

Generating a Table Dynamically

#!/usr/local/bin/python

print "Content-type: text/html\n\n"

print """
<html>  
        <head><title>Table Demo</title></head>  
        <body>    
        <h3>COMP249 Staff</h3>    
          <table> 
       <tr><th>Lecturer</th><th>Unit</th></tr>
"""
dict = {'Rolf':'COMP249','Steve':'COMP249'}
for key, value in dict.items():
    print "    <tr><td>", key, "</td><td>", value, "</td></tr>"
print """    
    </table>  
  </body>
</html>
"""

The HTML Form Code

<html>
  <head><title>A simple HTML Form Page</title><head>
  <body>
     <h3> A simple HTML Form Page</h3>
     <hr>
     <form action="cgi-bin/process.py">
       <p><strong>Enter your name:</strong></p>
       <p><input type=text name=user></p>
       <p><input type=submit></p>
     </form>
  <body>
<html>

CGI Script Processing

Diagram of CGI
	    process

The Query String Format

How is the Query String transmitted?

GET vs. POST

GET encodes the query string in the URL

GET vs. POST

Handling Form Data in Python

A Simple CGI Script

#!/share/bin/python

import cgi                            # imports cgi module
import cgitb; cgitb.enable()          # traceback manager, displays
                                      # errors in the Web browser
form = cgi.FieldStorage()             # retrieves form input
# define start and end of page
pagehead = """
<html>
  <head><title>Greetings</title></head>
  <body>
    <h3>Greetings</h3>"""
	
pagefoot = """  </body>
</html>
"""
      

A Simple CGI Script

print "Content_type: text/html\n\n"    
print pagehead                        
if 'user' not in form:
    print "<p>Who are you?</p>"
else:
    print "<p>Hello ", form.getvalue('user'), "</p>"
print pagefoot

Environment Variables

Environment Variables in Python

In Python, HTTP environment variables are available (when set) via the os.environ dictionary.

#!/share/bin/python

import os

print 'Content-type: text/html\n\n'

if os.environ.has_key('SERVER_PORT'):
    server_port = os.environ['SERVER_PORT']
    print '<p> SERVER_PORT:', server_port, '</p>'
else:
    print '<p> SERVER_PORT: unknown </p>'

Example

Query String

The QUERY_STRING variable always appears in the os.environ dictionary, even though its value is '' (the empty string).

#!/share/bin/python

import os

print 'Content-type: text/html\n\n'

if os.environ.has_key('QUERY_STRING') and  \               
           os.environ['QUERY_STRING'] != '':
     query_string = os.environ['QUERY_STRING']
     print '<h3> QUERY_STRING:', query_string, '</h3>'
else:
     print '<h3> QUERY_STRING: unknown </h3>'

Examples: name=Steve, name=Steve&age=21