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

(yzsuai) #1

print('Content-type: text/html\n') # wrap up in HTML
print('Languages')
print("

Source code: '%s'

" % filename)
print('
')
print(cgi.escape(open(filename).read())) # decode per platform default
print('

')


Here again, the filename is relative to the server’s directory for our web server on Win-
dows (see the prior discussion of this, and delete the cgi-bin portion of its path on
other platforms). When we visit this script on the Web via the first source hyperlink in
Example 15-17 or a manually typed URL, the script delivers a response to the client
that includes the text of the CGI script source file. It’s captured in Figure 15-27.


Figure 15-27. Source code viewer page


Note that here, too, it’s crucial to format the text of the file with cgi.escape, because
it is embedded in the HTML code of the reply. If we don’t, any characters in the text
that mean something in HTML code are interpreted as HTML tags. For example, the
C++ < operator character within this file’s text may yield bizarre results if not properly
escaped. The cgi.escape utility converts it to the standard sequence < for safe
embedding.


1210 | Chapter 15: Server-Side Scripting

Free download pdf