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
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 leapyear.py CGI script.
This code would be just a part of a complete Web page.
<p>Enter a year and find out if it's a leap year:
<input type="text" name="year" size="6">
The form's action attribute must be set to the path to your CGI
The CGI script
The following code is executed when the HTML form is submitted:
if year % 400 == 0:
elif year % 100 == 0:
elif year % 4 == 0:
reshtml = """Content-Type: text/html\n
<h1>Is it a leap year?</h1>
form = cgi.FieldStorage()
year = form['year'].value
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.