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 = """

Thanks for the Treat!

Meow!

Back

""" else: """The index welcome page""" contents = """

Cotton & Tulip Love Treats!

Click the Fish Below to Give Cotton and Tulip a Treat