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

(yzsuai) #1

This page contains a simple text field as before, but it also has radio buttons, a pull-
down selection list, a set of multiple-choice check buttons, and a multiple-line text
input area. All have a name option in the HTML file, which identifies their selected value
in the data sent from client to server. When we fill out this form and click the Send
submit button, the script in Example 15-12 runs on the server to process all the input
data typed or selected in the form.


Example 15-12. PP4E\Internet\Web\cgi-bin\tutor5.py


#!/usr/bin/python
"""
runs on the server, reads form input, prints HTML
"""


import cgi, sys
form = cgi.FieldStorage() # parse form data
print("Content-type: text/html") # plus blank line


html = """


tutor5.py

Greetings




Your name is %(name)s


You wear rather %(shoesize)s shoes


Your current job: %(job)s


You program in %(language)s


You also said:


%(comment)s



"""

data = {}
for field in ('name', 'shoesize', 'job', 'language', 'comment'):
if not field in form:
data[field] = '(unknown)'
else:
if not isinstance(form[field], list):
data[field] = form[field].value
else:
values = [x.value for x in form[field]]
data[field] = ' and '.join(values)
print(html % data)


This Python script doesn’t do much; it mostly just copies form field information into
a dictionary called data so that it can be easily inserted into the triple-quoted response
template string. A few of its techniques merit explanation:


Field validation
As usual, we need to check all expected fields to see whether they really are present
in the input data, using the dictionary in expression. Any or all of the input fields
may be missing if they weren’t entered on the form or appended to an explicit URL.


Climbing the CGI Learning Curve| 1165
Free download pdf