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

(yzsuai) #1

String formatting
We’re using dictionary key references in the format string this time—recall that %
(name)s means pull out the value for the key name in the data dictionary and perform
a to-string conversion on its value.


Multiple-choice fields
We’re also testing the type of all the expected fields’ values to see whether they
arrive as a list rather than the usual string. Values of multiple-choice input controls,
like the language choice field in this input page, are returned from
cgi.FieldStorage as a list of objects with value attributes, rather than a simple
single object with a value.
This script copies simple field values to the dictionary verbatim, but it uses a list
comprehension to collect the value fields of multiple-choice selections, and the
string join method to construct a single string with an and inserted between each
selection value (e.g., Python and Tcl). The script’s list comprehension is equivalent
to the call map(lambda x: x.value, form[field]).


Not shown here, the FieldStorage object’s alternative methods getfirst and getlist
can also be used to treat fields as single and multiple items, whether they were sent that
way or not (see Python’s library manuals). And as we’ll see later, besides simple strings
and lists, a third type of form input object is returned for fields that specify file uploads.
To be robust, the script should really also escape the echoed text inserted into the
HTML reply, lest it contain HTML operators; we will discuss escapes in detail later.


When the form page is filled out and submitted, the script creates the response shown
in Figure 15-14—essentially just a formatted echo of what was sent.


Changing Input Layouts


Suppose that you’ve written a system like that in the prior section, and your users,
clients, and significant other start complaining that the input form is difficult to read.
Don’t worry. Because the CGI model naturally separates the user interface (the HTML
input page definition) from the processing logic (the CGI script), it’s completely painless
to change the form’s layout. Simply modify the HTML file; there’s no need to change
the CGI code at all. For instance, Example 15-13 contains a new definition of the input
that uses tables a bit differently to provide a nicer layout with borders.


Example 15-13. PP4E\Internet\Web\tutor5b.html


CGI 101

Common input devices: alternative layout


Use the same tutor5.py server side script, but change the
layout of the form itself. Notice the separation of user interface
and processing logic here; the CGI script is independent of the
HTML used to interact with the user/client.



1166 | Chapter 15: Server-Side Scripting

Free download pdf