#!/usr/bin/python2 import cgi def main(): form = cgi.FieldStorage() # standard cgi script lines to here! name = form.getfirst("name", "no name") addr = form.getfirst("addr", "nowhere") line = "Name: %s Address: %s\n" % (name, addr) fileName= "namelist.txt" append(fileName, line) lines = fileLinesToHTMLLines(fileName) showPage("nameListOutput.html", lines ) def append(fileName, s): """Append string s to file with name fileName. This fails if there are multiple people trying. """ fout = open(fileName,'a') fout.write(s) fout.close() def fileLinesToHTMLLines(fileName): """Allow lines of the file with name fileName to be embedded in html. This fails if there are multiple people trying. """ fin = open(fileName,'r') s = fin.readlines() fin.close() return "
".join(s) def showPage(templateFileName, substitutions): # keep this handy function """ templateFileName is the string name of the html file used as a format string. substitutions is either a single data item or an explicit tuple containing the data to substitute into the format string in the file. The function prints the string created from the file's format string and the supplied substitutions. """ fin = open(templateFileName); #page could be a canned string page = fin.read(); # in the program but this allows the visual display fin.close() # to be changed separately from the logic. print page % substitutions #standard lines from here on try: print "Content-type: text/html\n\n" # say generating html main() except: cgi.print_exception() # catch and print errors