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

(yzsuai) #1

Most of the code changes in this version of the reply script are straightforward. If you
test-drive these pages, the only differences you’ll find are the URLs at the top of your
browser (they’re different files, after all), extra blank lines in the generated HTML
(ignored by the browser), and a potentially different ordering of language names in the
main page’s pull-down selection list.


Again, this selection list ordering difference arises because this version relies on the
order of the Python dictionary’s keys list, not on a hardcoded list in an HTML file.
Dictionaries, you’ll recall, arbitrarily order entries for fast fetches; if you want the se-
lection list to be more predictable, simply sort the keys list before iterating over it using
the list sort method or the sorted function introduced in Python 2.4:


for lang in sorted(hellos): # dict iterator instead of .keys()
mock = {inputkey: FieldMockup(lang)}

Faking Inputs with Shell Variables
If you’re familiar with shells, you might also be able to test CGI scripts from the com-
mand line on some platforms by setting the same environment variables that HTTP
servers set, and then launching your script. For example, we might be able to pretend
to be a web server by storing input parameters in the QUERY_STRING environment vari-
able, using the same syntax we employ at the end of a URL string after the ?:
$ setenv QUERY_STRING "name=Mel&job=trainer,+writer"
$ python tutor5.py
Content-type: text/html
<TITLE>tutor5.py<?TITLE>
<H1>Greetings</H1>
<HR>
<H4>Your name is Mel</H4>
<H4>You wear rather (unknown) shoes</H4>
<H4>Your current job: trainer, writer</H4>
<H4>You program in (unknown)</H4>
<H4>You also said:</H4>
<P>(unknown)</P>
<HR>
Here, we mimic the effects of a GET style form submission or explicit URL. HTTP servers
place the query string (parameters) in the shell variable QUERY_STRING. Python’s cgi
module finds them there as though they were sent by a browser. POST-style inputs can
be simulated with shell variables too, but it’s more complex—so much so that you may
be better off not bothering to learn how. In fact, it may be more robust in general to
mock up inputs with Python objects (e.g., as in formMockup.py). But some CGI scripts
may have additional environment or testing constraints that merit unique treatment.

More on HTML and URL Escapes


Perhaps the subtlest change in the last section’s rewrite is that, for robustness, this
version’s reply script (Example 15-23) also calls cgi.escape for the language name, not


More on HTML and URL Escapes | 1201
Free download pdf