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

(yzsuai) #1

through the script filename (and up to URL query parameters) are used in the conver-
sation between browser and HTTP server, before a CGI script is ever spawned. As long
as the browser knows which server to contact, the URL will work.


On the other hand, URLs submitted outside of a page (e.g., typed into a browser’s
address field or sent to the Python urllib.request module we’ll revisit later) usually
must be completely specified, because there is no notion of a prior page.


Response script


So far, we’ve created only a static page with an input field. But the Submit button on
this page is loaded to work magic. When pressed, it triggers the possibly remote pro-
gram whose URL is listed in the form’s action option, and passes this program the
input data typed by the user, according to the form’s method encoding style option. On
the server, a Python script is started to handle the form’s input data while the user waits
for a reply on the client; that script is shown in Example 15-8.


Example 15-8. PP4E\Internet\Web\cgi-bin\tutor3.py


#!/usr/bin/python
"""
runs on the server, reads form input, prints HTML;
url=http://server-name/cgi-bin/tutor3.py
"""


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


html = """


tutor3.py

Greetings




%s



"""

if not 'user' in form:
print(html % 'Who are you?')
else:
print(html % ('Hello, %s.' % form['user'].value))


As before, this Python CGI script prints HTML to generate a response page in the
client’s browser. But this script does a bit more: it also uses the standard cgi module
to parse the input data entered by the user on the prior web page (see Figure 15-6).


Luckily, this is automatic in Python: a call to the standard library cgi module’s Field
Storage class does all the work of extracting form data from the input stream and
environment variables, regardless of how that data was passed—in a post style stream
or in get style parameters appended to the URL. Inputs sent in both styles look the
same to Python scripts.


1152 | Chapter 15: Server-Side Scripting

Free download pdf