#!/usr/bin/python
#
# testcgi.py
#
# Simple example of Python CGI
#
# C. David Sherrill, January 2010
#
import cgi, sys, cgitb
import urllib # escape characters for HTML and URL's
cgitb.enable() # CGI traceback manager (help debugging)
form = cgi.FieldStorage() # parse form data
print "Content-type: text/html\n" # need the \n newline!
html_header = """
CGI Test
"""
html_footer = """
"""
htmlform = """
"
# send will equal Submit if the submit button has been pressed...
# can check this by adding this line to the html string above
# send = %(send)s
suppdata = {} # meta-data for form
# this loop only works if it is 2 or more items... need the comma if only 1
for field in ('send',):
if not form.has_key(field):
suppdata[field] = ""
else:
if type(form[field]) != list:
suppdata[field] = form[field].value
else:
values = [x.value for x in form[field]]
suppdata[field] = ' and '.join(values)
# Note: nextitem is supposed to be boolean
# print htmlform % data, where data is a dictionary with the keys above
# need to set managerchecked to "checked" (if manager) or "" if not
data = {}
for field in ('name', 'job', 'years', 'manager'):
if not form.has_key(field):
data[field] = ""
else:
if type(form[field]) != list:
data[field] = form[field].value
else:
values = [x.value for x in form[field]]
data[field] = ' and '.join(values)
if data['manager'] == "1":
suppdata['managerchecked'] = "checked"
else:
suppdata['managerchecked'] = ""
suppdata['years1'] = ""
suppdata['years2'] = ""
suppdata['years3'] = ""
if data['years'] == "1":
suppdata['years1'] = "selected"
elif data['years'] == "2":
suppdata['years2'] = "selected"
elif data['years'] == "3":
suppdata['years3'] = "selected"
# make sure this call is done after all changes to suppdata and data
# merge the data into suppdata
suppdata.update(data)
# Try to update the database if this was submitted
# and it is a new item
if (suppdata['send'] == "Submit"):
# do any testing of form data here
if (data['name'] == "" or data['job'] == ""):
print html_header
print htmlform % suppdata
print "Error: must fill in name and job fields!"
print html_footer
else:
# upload data to a database here
# print ok to the user
print html_header
print "Adding data to the database.
\n"
print "name=%s, job=%s, years=%s.
\n" % \
(data['name'], data['job'], data['years'])
print "Is",
if (data['manager'] == "1"):
print "a manager.
\n"
else:
print "not a manager.
\n"
print "New data submitted!
\n"
print html_footer
else: # if it wasn't submitted
print html_header
print htmlform % suppdata
print html_footer