Python Bibliotheca
Python resources for teachers and students.

Basic CGI scripting

As you can tell from the following code, turning a regular python program in to a CGI script can be quite easy. In this case all that was required was to add a triple-quoted string to produce the HTML and some simple form processing using the CGI module.

For more information about CGI programming with Python, check out the following resources:

The HTML form

Most interaction with CGI scripts is accomplished through Web forms. Here's the code for a very simple form that calls the CGI script. This code would be just a part of a complete Web page.

<form action="cgi-bin/">
 <p>Enter a year and find out if it's a leap year:
 <input type="text" name="year" size="6">
 <input type="submit">
 <input type="reset">

The form's action attribute must be set to the path to your CGI script.

The CGI script

The following code is executed when the HTML form is submitted:


import cgi

def isLeap(year):
   if year % 400 == 0:
       return 1
   elif year % 100 == 0:
       return 0
   elif year % 4 == 0:
       return 1
       return 0

reshtml = """Content-Type: text/html\n
 <head><title>Leap Year</title></head>

  <h1>Is it a leap year?</h1>

form = cgi.FieldStorage()
year = form['year'].value
if isLeap(int(year)):
    message = "%s is a leap year." % year
    message = "%s is not a leap year." % year
print reshtml % message

Don't forget to set the Content-Type header at the beginning of the generated HTML. Without it, the Web server won't know what to do with it. Notice how the results of the leap year calculation are inserted into the HTML code by using the %s code in the reshtml string.

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster