#!/usr/bin/python import re import cgi # specify the filename of the template file TemplateFile = "template.html" # specify the filename of the form to show the user FormFile = "form.htm" # Display takes one parameter - a string to Display def Display(Content): TemplateHandle = open(TemplateFile, "r") # open in read only mode # read the entire file as a string TemplateInput = TemplateHandle.read() TemplateHandle.close() # close the file # this defines an exception string in case our # template file is messed up BadTemplateException = "There was a problem with the HTML template." SubResult = re.subn("", Content,TemplateInput) if SubResult[1] == 0: raise BadTemplateException print "Content-Type: text/html\n\n" print SubResult[0] ### what follows are our two main 'action' functions, one to show the ### form, and another to process it # this is a really simple function def DisplayForm(): FormHandle = open(FormFile, "r") FormInput = FormHandle.read() FormHandle.close() Display(FormInput) def ProcessForm(form): # extract the information from the form in easily digestible format try: name = form["name"].value except: # name is required, so output an error if # not given and exit script Display("You need to at least supply a name. Please go back.") raise SystemExit try: email = form["email"].value except: email = None try: color = form["color"].value except: color = None try: comment = form["comment"].value except: comment = None Output = "" # our output buffer, empty at first Output = Output + "Hello, " if email != None: Output = Output + "" + name + ".
" else: Output = Output + name + ".
" if color == "swallow": Output = Output + "You must be a Monty Python fan.
" elif color != None: Output = Output + "Your favorite color was " + color + "
" else: Output = Output + "You cheated! You didn't specify a color!
"
if comment != None:
Output = Output + "In addition, you said:
" + comment + "
" Display(Output) ### ### Begin actual script ### ### evaluate CGI request form = cgi.FieldStorage() ### "key" is a hidden form element with an ### action command such as "process" try: key = form["key"].value except: key = None if key == "process": ProcessForm(form) else: DisplayForm()