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

(yzsuai) #1

values imported from the common module. It’s otherwise similar to the original HTML
file’s code; when we visit this script’s URL, we get a similar page, shown in Fig-
ure 15-25. But this time, the page is generated by running a script on the server that
populates the pull-down selection list from the keys list of the common syntax table.
Use your browser’s View Source option to see the HTML generated; it’s nearly identical
to the HTML file in Example 15-17, though the order of languages in the list may differ
due to the behavior of dictionary keys.


Figure 15-25. Alternative main page made by languages2.py


One maintenance note here: the content of the REPLY HTML code template string in
Example 15-20 could be loaded from an external text file so that it could be worked on
independently of the Python program logic. In general, though, external text files are
no more easily changed than Python scripts. In fact, Python scripts are text files, and
this is a major feature of the language—it’s easy to change the Python scripts of an
installed system on site, without recompile or relink steps. However, external HTML
files could be checked out separately in a source-control system, if this matters in your
environment.


Step 2: A Reusable Form Mock-Up Utility


Moving the languages table and input field name to a module file solves the first two
maintenance problems we noted. But if we want to avoid writing a dummy field mock-
up class in every CGI script we write, we need to do something more. Again, it’s merely
a matter of exploiting the Python module’s affinity for code reuse: let’s move the
dummy class to a utility module, as in Example 15-21.


1196 | Chapter 15: Server-Side Scripting

Free download pdf