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

(yzsuai) #1

Also note that the CGI script in Example 1-31 isn’t printing complete HTML: the


and tags of the static HTML file in Example 1-30 are missing. Strictly
speaking, such tags should be printed, but web browsers don’t mind the omissions,
and this book’s goal is not to teach legalistic HTML; see other resources for more on
HTML.

GUIs versus the Web


Before moving on, it’s worth taking a moment to compare this basic CGI example with
the simple GUI of Example 1-28 and Figure 1-6. Here, we’re running scripts on a server
to generate HTML that is rendered in a web browser. In the GUI, we make calls to
build the display and respond to events within a single process and on a single machine.
The GUI runs multiple layers of software, but not multiple programs. By contrast, the
CGI approach is much more distributed—the server, the browser, and possibly the
CGI script itself run as separate programs that usually communicate over a network.


Because of such differences, the standalone GUI model may be simpler and more direct:
there is no intermediate server, replies do not require invoking a new program, no
HTML needs to be generated, and the full power of a GUI toolkit is at our disposal.
On the other hand, a web-based interface can be viewed in any browser on any com-
puter and only requires Python on the server machine.


And just to muddle the waters further, a GUI can also employ Python’s standard library
networking tools to fetch and display data from a remote server (that’s how web
browsers do their work internally), and some newer frameworks such as Flex, Silver-
light, and pyjamas provide toolkits that support more full-featured user interfaces
within web pages on the client (the RIAs I mentioned earlier), albeit at some added cost
in code complexity and software stack depth. We’ll revisit the trade-offs of the GUI
and CGI schemes later in this book, because it’s a major design choice today. First, let’s
preview a handful of pragmatic issues related to CGI work before we apply it to our
people database.


Running a Web Server


Of course, to run CGI scripts at all, we need a web server that will serve up our HTML
and launch our Python scripts on request. The server is a required mediator between
the browser and the CGI script. If you don’t have an account on a machine that has
such a server available, you’ll want to run one of your own. We could configure and
run a full production-level web server such as the open source Apache system (which,
by the way, can be tailored with Python-specific support by the mod_python extension).
For this chapter, however, I instead wrote a simple web server in Python using the code
in Example 1-32.


We’ll revisit the tools used in this example later in this book. In short, because Python
provides precoded support for various types of network servers, we can build a


Step 6: Adding a Web Interface | 55
Free download pdf