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

(yzsuai) #1

Syntax


"""

langhtml = """


%s


%s


"""

def showHello(form): # HTML for one language
choice = form[inputkey].value # escape lang name too
try:
print(langhtml % (cgi.escape(choice),
cgi.escape(hellos[choice])))
except KeyError:
print(langhtml % (cgi.escape(choice),
"Sorry--I don't know that language"))


def main():
if debugme:
form = {inputkey: FieldMockup(sys.argv[1])} # name on cmd line
else:
form = cgi.FieldStorage() # parse real inputs


print(hdrhtml)
if not inputkey in form or form[inputkey].value == 'All':
for lang in hellos.keys():
mock = {inputkey: FieldMockup(lang)} # not dict(n=v) here!
showHello(mock)
else:
showHello(form)
print('


')


if name == 'main': main()


When global debugme is set to True, the script can be tested offline from a simple com-
mand line as before:


C:\...\PP4E\Internet\Web\cgi-bin> python languages2reply.py Python
Content-type: text/html

<TITLE>Languages</TITLE>
<H1>Syntax</H1><HR>

<H3>Python</H3><P><PRE>
print('Hello World')
</PRE></P><BR>
<HR>

When run online using either the page in Figure 15-25 or an explicitly typed URL with
query parameters, we get the same reply pages we saw for the original version of this
example (we won’t repeat them here again). This transformation changed the pro-
gram’s architecture, not its user interface. Architecturally, though, both the input and
reply pages are now created by Python CGI scripts, not static HTML files.


1200 | Chapter 15: Server-Side Scripting

Free download pdf