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

(yzsuai) #1
>>> from urllib.request import urlopen
>>> request = 'http://localhost/cgi-bin/languages.py?language=Python'
>>> reply = urlopen(request).read()
>>> print(reply.decode())
<TITLE>Languages</TITLE>
<H1>Syntax</H1><HR>
<H3>Python</H3><P><PRE>
print('Hello World')
</PRE></P><BR>
<HR>

To be robust, though, the script also checks for both error cases explicitly, as all CGI
scripts generally should. Here is the HTML generated in response to a request for the
fictitious language GuiDO (again, you can also see this by selecting your browser’s
View Source option after typing the URL manually into your browser’s address field):


>>> request = 'http://localhost/cgi-bin/languages.py?language=GuiDO'
>>> reply = urlopen(request).read()
>>> print(reply.decode())
<TITLE>Languages</TITLE>
<H1>Syntax</H1><HR>
<H3>GuiDO</H3><P><PRE>
Sorry--I don't know that language
</PRE></P><BR>
<HR>

If the script doesn’t receive any language name input, it simply defaults to the “All”
case (this case is also triggered if the URL ends with just ?language= and no language
name value):


>>> reply = urlopen('http://localhost/cgi-bin/languages.py').read()
>>> print(reply.decode())
<TITLE>Languages</TITLE>
<H1>Syntax</H1><HR>
<H3>C</H3><P><PRE>
printf("Hello World\n");
</PRE></P><BR>
<H3>Java</H3><P><PRE>
System.out.println("Hello World");
</PRE></P><BR>
<H3>C++</H3><P><PRE>
cout << "Hello World" << endl;
</PRE></P><BR>
...more...

If we didn’t detect these cases, chances are that our script would silently die on a Python
exception and leave the user with a mostly useless half-complete page or with a default
error page (we didn’t assign stderr to stdout here, so no Python error message would
be displayed). Figure 15-24 shows the page generated and rendered by a browser if the
script is invoked with an explicit URL like this:


http://localhost/cgi-bin/languages.py?language=COBOL

The Hello World Selector | 1191
Free download pdf