[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1






To handle form (and other) requests, Example 1-34 implements a Python CGI script
that fetches and updates our shelve’s records. It echoes back a page similar to that
produced by Example 1-33, but with the form fields filled in from the attributes of
actual class objects in the shelve database.


As in the GUI, the same web page is used for both displaying results and inputting
updates. Unlike the GUI, this script is run anew for each step of user interaction, and
it reopens the database each time (the reply page’s action field provides a link back to
the script for the next request). The basic CGI model provides no automatic memory
from page to page, so we have to start from scratch each time.


Example 1-34. PP4E\Preview\cgi-bin\peoplecgi.py


"""
Implement a web-based interface for viewing and updating class instances
stored in a shelve; the shelve lives on server (same machine if localhost)
"""


import cgi, shelve, sys, os # cgi.test() dumps inputs
shelvename = 'class-shelve' # shelve files are in cwd
fieldnames = ('name', 'age', 'job', 'pay')


form = cgi.FieldStorage() # parse form data
print('Content-type: text/html') # hdr, blank line is in replyhtml
sys.path.insert(0, os.getcwd()) # so this and pickler find person


main html template


replyhtml = """



People Input Form



key
$ROWS$






"""

insert html for data rows at $ROWS$


rowhtml = '%s\n'
rowshtml = ''
for fieldname in fieldnames:
rowshtml += (rowhtml % ((fieldname,) * 3))


Step 6: Adding a Web Interface | 61
Free download pdf