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

(yzsuai) #1
we could achieve similar results with a default argument in showHello, albeit at the
cost of introducing a special case in its code.

Now back to interacting with this program. If we select a particular language, our CGI
script generates an HTML reply of the following sort (along with the required content-
type header and blank line preamble). Use your browser’s View Source option to see:


<TITLE>Languages</TITLE>
<H1>Syntax</H1><HR>
<H3>Scheme</H3><P><PRE>
(display "Hello World") (newline)
</PRE></P><BR>
<HR>

Program code is marked with a

 tag to specify preformatted text (the browser
won’t reformat it like a normal text paragraph). This reply code shows what we get
when we pick Scheme. Figure 15-22 shows the page served up by the script after se-
lecting “Python” in the pull-down selection list (which, for the purposes of both this
edition and the expected future at large, of course, really means Python 3.X).


Figure 15-22. Response page created by languages.py


Our script also accepts a language name of “All” and interprets it as a request to display
the syntax for every language it knows about. For example, here is the HTML that is
generated if we set the global variable debugme to True and run from the system com-
mand line with a single argument, All. This output is the same as what is printed to
the client’s web browser in response to an “All” selection*:



  • We also get the “All” reply if debugme is set to False when we run the script from the command line. Instead
    of throwing an exception, the cgi.FieldStorage call returns an empty dictionary if called outside the CGI
    environment, so the test for a missing key kicks in. It’s likely safer to not rely on this behavior, however.


1188 | Chapter 15: Server-Side Scripting

Free download pdf