Listing 2. The Final Python CGI Code #!/usr/bin/python import serial import cgi from Cheetah.Template import Template import shelve t = Template(open('feeder.tmpl.py').read()) port = serial.Serial(0) class Feeder: def __init__(self): self.total_fed = 0 def feed(self): self.total_fed = self.total_fed + 1 port.write("B") def getTotalFed(self): return self.total_fed print 'Content-Type: text/html' print # Blank line marking end of HTTP headers form = cgi.FieldStorage() d = shelve.open("feeder.dbm") if d.has_key("control"): """ if shelf file exists, open it, otherwise create it and a new instance of the Feeder class """ control = d['control'] else: control = Feeder() d['control'] = control if form.has_key("command") and \ form['command'].value == 'feed': """ if we received the feed command, feed, otherwise, show the index page""" control.feed() contents = """ <p class="header"> Thanks for the Treat!</p> <p class="body">Meow!</p> <p valign="bottom"> <a href="index.py">Back</a></p>""" else: """The index welcome page""" contents = """ <p class="header">Cotton & Tulip Love Treats!</p> <p class="body"> Click the Fish Below to Give Cotton and Tulip a Treat</p> <p><a href="index.py?command=feed"> <img border="0" src="images/dance_fish.gif"> </a></p> <p><br><p> <p class="footer" valign="bottom"> The kitten feeder is an honest to goodness device attached to a Linux Server in Chris and Camri's apartment. """ """Set the variables that Cheetah will use""" t.contents = contents t.fed = control.getTotalFed() """Print the complete Page""" print t """Save the control to our shelf""" d['control'] = control d.close()