Sending 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 12-23,
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
pre-formatted text, and escaped for transmission inside HTML with
cgi.escape
.
Example 12-23. PP2E\Internet\Cgi-Web\Basics\languages-src.cgi
#!/usr/bin/python ################################################################# # Display languages.cgi script code without running it. ################################################################# import cgi filename = 'languages.cgi' 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>'
When we visit this script on the Web via the hyperlink or a manually typed URL, the script delivers a response to the client that includes the text of the CGI script source file. It appears as in Figure 12-25.
Figure 12-25. Source code viewer page
Note that here, too, it’s crucial to format the text ...
Get Programming Python, Second 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.