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

(yzsuai) #1

full-blown Python installation on the server. The public domain PyInstaller and Py2Exe
systems can produce a frozen Python binary.


Finally, to run this book’s examples, make sure the Python you find or install is Python
3.X, not Python 2.X. As mentioned earlier, many commercial ISPs support the latter
but not the former as I’m writing this fourth edition, but this is expected to change over
time. If you do locate a commercial ISP with 3.X support, you should be able to upload
your files by FTP and work by SSH or Telnet. You may also be able to run this chapter’s
webserver.py script on the remote machine, though you may need to avoid using the
standard port 80, depending on how much control your account affords.


Adding Pictures and Generating Tables


Let’s get back to writing server-side code. As anyone who’s ever surfed the Web knows,
web pages usually consist of more than simple text. Example 15-4 is a Python CGI
script that prints an HTML tag in its output to produce a graphic image in the
client browser. This example isn’t very Python-specific, but note that just as for simple
HTML files, the image file (ppsmall.gif, one level up from the script file) lives on and is
downloaded from the server machine when the browser interprets the output of this
script to render the reply page (even if the server’s machine is the same as the client’s).


Example 15-4. PP4E\Internet\Web\cgi-bin\tutor1.py


#!/usr/bin/python


text = """Content-type: text/html


CGI 101

A Second CGI Script




Hello, CGI World!


[image]


"""

print(text)


Notice the use of the triple-quoted string block here; the entire HTML string is sent to
the browser in one fell swoop, with the print call statement at the end. Be sure that the
blank line between the Content-type header and the first HTML is truly blank in the
string (it may fail in some browsers if you have any spaces or tabs on that line). If both
client and server are functional, a page that looks like Figure 15-4 will be generated
when this script is referenced and run.


So far, our CGI scripts have been putting out canned HTML that could have just as
easily been stored in an HTML file. But because CGI scripts are executable programs,
they can also be used to generate HTML on the fly, dynamically—even, possibly, in
response to a particular set of user inputs sent to the script. That’s the whole purpose


1146 | Chapter 15: Server-Side Scripting

Free download pdf