Transferring Files to Clients and Servers
It’s time to explain a bit of HTML code we’ve been
keeping in the shadows. Did you notice those hyperlinks on the
language selector example’s main page for showing the CGI script’s
source code? Normally, we can’t see such script source code, because
accessing a CGI script makes it execute (we can see only its HTML
output, generated to make the new page). The script in Example 16-26, referenced by a
hyperlink in the main language.html
page, works around that by opening the source file and sending its
text as part of the HTML response. The text is marked with <PRE>
as preformatted text, and is
escaped for transmission inside HTML with cgi.escape
.
Example 16-26. PP3E\Internet\Web\cgi-bin\languages-src.py
#!/usr/bin/python ################################################################# # Display languages.py script code without running it. ################################################################# import cgi filename = 'cgi-bin/languages.py' print "Content-type: text/html\n" # wrap up in HTML print "<TITLE>Languages</TITLE>" print "<H1>Source code: '%s'</H1>" % filename print '<HR><PRE>' print cgi.escape(open(filename).read( )) print '</PRE><HR>'
Here again, the filename
is
relative to the server’s directory for our web server on Windows (see
the prior note, and delete the cgi-bin
portion of its path on other platforms). When we visit this script on the Web via the hyperlink or a manually typed URL, the script delivers a response ...
Get Programming Python, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.