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

(yzsuai) #1

when I wrote this chapter in mid-2010, though it’s possible to find commercial ISPs
today that do. Naturally, this may change over time.


Running a Local Web Server


To keep things simple, this edition is taking a different approach. All the examples will
be run using a simple web server coded in Python itself. Moreover, the web server will
be run on the same local machine as the web browser client. This way, all you have to
do to run the server-side examples is start the web server script and use “localhost” as
the server name in all the URLs you will submit or code (see Chapter 12 if you’ve
forgotten why this name means the local machine). For example, to view a web page,
use a URL of this form in the address field of your web browser:


http://localhost/tutor0.html

This also avoids some of the complexity of per-server differences, and it makes changing
the code simple—it can be edited on the local machine directly.


For this book’s examples, we’ll use the web server in Example 15-1. This is essentially
the same script introduced in Chapter 1, augmented slightly to allow the working di-
rectory and port number to be passed in as command-line arguments (we’ll also run
this in the root directory of a larger example in the next chapter). We won’t go into
details on all the modules and classes Example 15-1 uses here; see the Python library
manual. But as described in Chapter 1, this script implements an HTTP web server,
which:



  • Listens for incoming socket requests from clients on the machine it is run on and
    the port number specified in the script or command line (which defaults to 80, that
    standard HTTP port)

  • Serves up HTML pages from the webdir directory specified in the script or com-
    mand line (which defaults to the directory it is launched from)

  • Runs Python CGI scripts that are located in the cgi-bin (or htbin) subdirectory of
    the webdir directory, with a .py filename extension


See Chapter 1 for additional background on this web server’s operation.


Example 15-1. PP4E\Internet\Web\webserver.py


"""
Implement an HTTP web server in Python which knows how to serve HTML
pages and run server-side CGI scripts coded in Python; this is not
a production-grade server (e.g., no HTTPS, slow script launch/run on
some platforms), but suffices for testing, especially on localhost;


Serves files and scripts from the current working dir and port 80 by
default, unless these options are specified in command-line arguments;
Python CGI scripts must be stored in webdir\cgi-bin or webdir\htbin;
more than one of this server may be running on the same machine to serve
from different directories, as long as they listen on different ports;


Running Server-Side Examples | 1131
Free download pdf