#!/usr/bin/python2 # -*- coding: utf-8 -*- import cgi form=cgi.FieldStorage() who = form.getvalue('who') print "Content-Type: text/html" # ALWAYS this header (HTML is following) # more headers, such as Set-Cookie: if (who): print "Set-Cookie: whop=%s" % who print "Set-Cookie: who=%s; Path=/~jensen" % who #available to your php and html pages, but NOT to other python scripts print # blank line, end of headers print """ """ # -------------- fetch a cookie in our path (/cgi-bin ....) import Cookie import os try: cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) print "Welcome back " + cookie["whop"].value except (Cookie.CookieError, KeyError): print "First python order" import psycopg2 try: con=psycopg2.connect('dbname=fruitstand') except: print "Database connect trouble" import sys sys.exit() curs=con.cursor() # get a dictionary of prices curs.execute("select trim(name), price from fruit where stock>0") prices={} for f,p in curs.fetchall(): prices[f]=float(p) print "

Super Mario's Fruits, Thank you" print who, print """

You have ordered: """ curs.execute ("insert into sales values (%(who)s)", {'who':who}) con.commit() sum = 0.0 for fruit in form.keys(): qty = form.getvalue(fruit) if fruit != 'who' and qty > '0': qty=int(qty) try: curs.execute("insert into sold values (%(f)s,%(q)s)", {'f':fruit,'q':qty}) con.commit() price=prices[fruit] # look up in a dict! print "" %\ (fruit, qty, price, qty*price) sum += qty*price except: print "" % (fruit, qty) con.rollback() # if insert went wrong, this "resets" to allow further inserts # all done, commit the last transaction, and print the sum print ""\ % (sum) con.commit() # make changes stick, and close cursor and connection curs.close() con.close() print """
FruitQuantityPriceTotal
%s%d%.2f%.2f
%sSeems we don't have %d
Total for all$ %.2f
"""