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

(yzsuai) #1

class dummy: # mocked-up input obj
def init(self, str): self.value = str


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


print('Content-type: text/html\n') # adds blank line
print('Languages')
print('

Syntax


')


def showHello(form): # HTML for one language
choice = form[inputkey].value
print('

%s

' % choice)
try:
print(cgi.escape(hellos[choice]))
except KeyError:
print("Sorry--I don't know that language")
print('


')


if not inputkey in form or form[inputkey].value == 'All':
for lang in hellos.keys():
mock = {inputkey: dummy(lang)}
showHello(mock)
else:
showHello(form)
print('


')


And as usual, this script prints HTML code to the standard output stream to produce
a response page in the client’s browser. Not much is new to speak of in this script, but
it employs a few techniques that merit special focus:


Raw strings and quotes
Notice the use of raw strings (string constants preceded by an “r” character) in the
language syntax dictionary. Recall that raw strings retain \ backslash characters in
the string literally, instead of interpreting them as string escape-code introductions.
Without them, the \n newline character sequences in some of the language’s code
snippets would be interpreted by Python as line feeds, instead of being printed in
the HTML reply as \n. The code also uses double quotes for strings that embed an
unescaped single-quote character, per Python’s normal string rules.


Escaping text embedded in HTML and URLs
This script takes care to format the text of each language’s code snippet with the
cgi.escape utility function. This standard Python utility automatically translates
characters that are special in HTML into HTML escape code sequences, so that
they are not treated as HTML operators by browsers. Formally, cgi.escape trans-
lates characters to escape code sequences, according to the standard HTML
convention: <, >, and & become <, >, and &. If you pass a second true
argument, the double-quote character (") is translated to ".


1186 | Chapter 15: Server-Side Scripting

Free download pdf