- Information Sources
- Web Server Architectures
- HTML (and XML) Generation
- Component Interaction: Choose Your Model
- Summary
HTML (and XML) Generation
There are as many ways to generate HTML in Python as there are to persuade Python scripts to interact with a web server. Some approaches are more complete, some better known, than others. A first stopping point might be http://www.python.org/topics/web/HTML.html, which lists some possibilities but by no means all.
The Python world is full of projects that start, show promising results, and then run out of steam before all the loose ends are tied up and the whole packaged up for convenient use. When it comes to HTML generation, the situation is no different, with some initially promising packages still in alpha after two years lying fallow and release numbers between 0.1 and 0.5 quite common. I suspect that sometimes this is due to the 80/20 rule, which suggests that you can get 80 percent of the return on a project for 20 percent of the investment. When you are writing open-source code, the last 20 percent can seem not worth four times the effort to date, particularly if other projects are further along.
Whether there is any way to stop such duplication of effort is another question. Web sites such as SourceForge and FreshMeat do a good job of publicizing projects in need of assistance, but many other projects are undertaken independently. At least those who start a project but do not complete it have learned a lot about writing software, besides picking up some programming technique. It takes more than just a good programmer to bring a project to completion.
Despite these gloomy ponderings, there are some exceptionally bright spots in the HTML landscape and some approaches you should know about whether you intend to adopt them or choose a "roll-out-your-own" approach. Because of their diversity it is only possible to pick a representative sample. You will find many other tools on the web that do similar things, and the ones you read about here are simply the best-known.
Programmed Techniques
The most flexible way to generate HTML is by writing code (Python, naturally), so this first section outlines the most popular way of doing that. These systems are equally suitable for producing static content but are not limited to that role.
HTMLgen
This module (found at http://starship.python.net/crew/friedrich/HTMLgen/html/main.html) is probably the best-known way of generating HTML. It defines an object hierarchy that closely parallels the hierarchy of HTML elements. Each object is capable of rendering itself in HTML, which it does when you call its __str__() method. Because the print statement also calls this method, you can generate a whole document by assembling components, appending the components to the document, and printing the document. This outputs the required HTML. Here is a simple interactive example:
>>> import HTMLgen >>> lst = HTMLgen.List() >>> lst.append("hello") >>> lst.append("everybody run!") >>> lst.append("goodbye") >>> print lst <UL> <LI>hello <LI>everybody run! <LI>goodbye </UL>
The general approach is to create some sort of document and then append content to it until you have assembled the whole page. You can build the content in chunks, in the same way as the preceding list. HTMLgen also allows you to use several different base objects for your document, including a SeriesDocument. This last is an interesting object because you can parameterize the characteristics of a whole series of documents in an initialization file and even link the set with pointers to "up," "previous," "next," and "home" documents of every page. This makes it easy to build coherent document sets composed of static content.
Albatross
Albatross (http://www.object-craft.com.au/projects/albatross) is a small open-source toolkit for constructing highly stateful web applications. The toolkit includes an extensible HTML templating system similar to Zope DTML. Although templates can be used standalone, Albatross also provides an application framework. A number of different mixin classes enable applications to be deployed either as CGI programs or, to improve efficiency, via mod_python. Application state can be stored either at the server or client. Albatross uses distutils for installation and provides a reasonably complete programming guide that covers all toolkit features.
Listing 16.7 is a simple CGI program that uses Albatross templates to display the CGI process environment. It creates a SimpleContext object in line 5 and on line 8 makes the os.environ dictionary available to the template under the name environ.
Listing 16.7 A Simple Albatross CGI Script
1 #!/usr/bin/python 2 import os 3 import albatross 4 5 ctx = albatross.SimpleContext('.') 6 templ = ctx.load_template('showenv.html') 7 8 ctx.locals.environ = os.environ 9 10 templ.to_html(ctx) 11 print 'Content-Type: text/html' 12 print 13 ctx.flush_html()
The templating system uses the locals member of the execution context as the local namespace for evaluating Python expressions. You can see in Listing 16.8 that the template iterates over the os.environ dictionary, which is accessible inside the template as a result of line 8 of Listing 16.7.
Listing 16.8 Accessing Execution Context in an Albatross Template
1 <html> 2 <head> 3 <title>The CGI environment</title> 4 </head> 5 <body> 6 <table> 7 <al-exec expr="keys = environ.keys(); keys.sort()"> 8 <al-for iter="name" expr="keys"> 9 <tr> 10 <td><al-value expr="name.value()"></td> 11 <td><al-value expr="environ[name.value()]"></td> 12 <tr> 13 </al-for> 14 </table> 15 </body> 16 </html>
When you use Albatross to build an application, the execution context becomes the session object, and each page is implemented by a Python page module (or object) plus one or more template files. Each page module contains a page_process() function to handle browser requests and a page_display() function to generate the response. Listing 16.9 is the login.py page module from the Albatross popview example application.
Listing 16.9 login.py from Albatross's popview Example
1 import poplib 2 3 def page_process(self, ctx): 4 if ctx.req_equals('login'): 5 if ctx.locals.username and ctx.locals.passwd: 6 try: 7 ctx.open_mbox() 8 ctx.add_session_vars('username', 'passwd') 9 except poplib.error_proto: 10 return 11 ctx.set_page('list') 12 13 def page_display(self, ctx): 14 ctx.run_template('login.html')
Ad Hoc Methods
If you do not have too much HTML to generate, and it is not important to be able to update the style of a set of pages with a single change, the techniques used in previous web examples in the book might be acceptable. Just parameterize HTML snippets with Python formatting symbols and use the string formatting (%) operator to insert the variable content you need. This technique certainly works for small webs, but the larger the web and the greater the amount of content, the more difficult this approach is to maintain. You need to be systematic if your approach is to scale up to large webs, so you should usually reserve ad hoc methods for experimentation, or for smaller systems where the work does not become too tedious.
Templating Tools
Sometimes there is simply too much detail in the HTML of a site to program it directly. This certainly applies when you want to take advantage of the visual effects of the newest WYSIWYG HTML generators but insert your own content inside the frameworks they produce. For these and other reasons the technique of filling in a template with variable content is a popular one, and many authors have produced useful results this way.
Cheetah
Cheetah (http://www.cheetahtemplate.org/) is an interesting template utility that can be used with equal facility to generate HTML, XML, PostScript, and any number of other formats. Four main principles guide its design:
Easy separation of content, code, and graphic design
Easy integration of content, code, and graphic design
Limit complexity, and use programming for difficult cases
Easily understood by non-programmers
The simple example from the Cheetah documentation shown in Listing 16.10 gives you the idea.
Listing 16.10 A Simple Cheetah HTML Definition
1 <HTML> 2 <HEAD><TITLE>$title</TITLE></HEAD> 3 <BODY> 4 5 <TABLE> 6 #for $client in $clients 7 <TR> 8 <TD>$client.surname, $client.firstname</TD> 9 <TD><A HREF="mailto:$client.email">$client.email</A></TD> 10 </TR> 11 #end for 12 </TABLE> 13 14 </BODY> 15 </HTML>
You can see that the dollar sign triggers variable substitution. Cheetah calls strings with these leading dollar signs placeholders. The placeholders are arbitrary Python expressions (with some syntax modifications to adapt to non-programmer use), which Cheetah evaluates when it renders the template. In very broad terms, a Cheetah template takes a definition such as the one in Listing 16.10 and a namespace (which is a Python dictionary). When you tell the template to render, it uses the namespace as the evaluation context for any placeholders it comes across in the definition. As with the UNIX shell, the placeholder following the dollar sign can be surrounded by braces to separate it from surrounding text if no spaces can be inserted.
An interesting design decision, based on the requirement that Cheetah be comprehensible to non-programmers, was to represent dictionary lookup by name qualification. Thus, if the namespace contained a variable client, which was bound to a dictionary such as {"firstname": "Steve", "surname": "Holden", "email": "sholden@holdenweb.com"}, then the previous example would access the elements of the dictionary. You can still use subscripting if you want, but most non-programmers find the qualified name notation much easier to work with.
For more complex data structures, the namespace used in a template can actually be a search list, which is a sequence of namespaces that Cheetah searches in turn until the required definition is found. This simple technique allows the creation of templates with a hierarchy of namespaces. Further, a placeholder can evaluate to another template, which is then itself evaluated, allowing Cheetah templates to be easily nested inside one another.
As you can observe in Listing 16.10, you can also include directives preceded by a pound sign. Some of these are Python statement constructs, interpreted much as you would expect. Others are specific constructs not related to Python. There are also macro definition facilities, which are beyond the scope of this short description. These features give you access to Python for anything that is too complex to perform using the standard placeholder features.
The Webware project has adopted Cheetah as its standard for template substitution of content. Although the software is still in beta at the time of writing, it is already stable and easy to use either with or without Webware. It looks as though Cheetah will be useful to many web projects, as well as any others that need flexible template substitution of a general nature.
Python Server Pages (PSP)
Confusingly, there are at least two systems going by the name of Python Server Pages, which should be no surprise. The version by Kirby Angell at http://www.ciobriefings.com/psp/ comes with a long license I did not have time to read and appears to combine Jython (or is it really JPython) with a servlet engine.
The PSP for Webware engine at http://writewithme.com/Webware/PSP/Documentation/PSP.html, whose primary author is Jay Love, declares itself on its home page to be open-source and therefore commanded attention rather more immediately. From now on, this is what I refer to when I mention PSP, but I cannot determine whether the name has any trademark status.
PSP processes three special constructs:
<%@ ... %>Directives import allows you to import other Python modules. extends defines the base class of the current page, in the spirit of Java. method is used to define new methods of the class being defined by the current file. Various other directives are concerned with Webware organization, and, finally, include is pretty obvious.
<%= ... %>Expressions In a similar vein to ASP, the engine replaces such constructs with the value of the bracketed expression.
<% ... %>Script blocks These can span several lines, and three reserved variables are defined for use inside the blocks: res the response object, including a write() method; req the request object, containing web inputs; trans the transaction object, which provides a context for successive Webware page interactions handled by the same servlets.
Because PSP actually generates a Webware method body, normal text (not a directive, expression, or script block) gets wrapped in code that sends it out through the server. The code in script blocks is copied verbatim into the method. There is a special <end> tag you can use to close an indented Python suite that spans multiple script blocks.
Yaptu
Yaptu, by Alex Martelli, (available at URL http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305) stands for "Yet Another Python Templating Utility." Like Cheetah, it is not specifically geared to HTML, but rather suited to any kind of text-based document (for example, RTF, LaTeX, even plain text, as well as HTML and so on). Unlike Cheetah, Yaptu does not alter Python syntax. Yaptu lets the user define which specific regular expressions denote a placeholder (an arbitrary Python expression) and the beginning, continuation, and end of arbitrary Python statements. This ensures that Yaptu markup can indeed be used for any kind of document, since the regular expressions can be chosen to avoid any conflict with the syntax of the language of that document.
Yaptu's main claim to fame is that, despite its generality, net of comments, and docstrings, it comprises just 50 lines of codelightweight enough to carry around wherever needed. This requires a compromise: if a Python clause to be embedded as Yaptu markup ends with a colon (such as an if condition:, for example), it must not be followed by a comment; if a clause does not end with a colon (such as a break statement, for example), it must be followed by a comment. If such restrictions, or some aspect of Python syntax, should prove unacceptable for a given application, Yaptu supplies two "hooks" making it easy for the application programmer to tailor things further. The application programmer can pass a "preprocessor" routine that gets a chance to manipulate all Yaptu-markup strings (expressions and statements) before Python sees them; and, for expressions only, a "handler" routine, that gets a chance to return a result and continue the templating process if an exception is raised while evaluating an expression.
Together with the capability to supply Yaptu with an arbitrary mapping to be used for "variable values" and arbitrary objects playing the roles of "input" (sources) and "output" (targets), Yaptu packs quite a punch for such a small and simple utility. It is instructive to examine the richly commented and documented source, and the internals-oriented discussion, at the previously mentioned "Python Cookbook" URL.
User Interaction Control
An important requirement is to be able to define interactions with the user in much the same way that you define interactions between software components. You have to be more careful with users, of course, since their behaviors are not programmed, and you can therefore expect them to provide dangerous operating systems commands as first and last names simply in the hope of seeing what they can provoke. If you examined the pyforms form handling module and the pySQL module for the Xitami example earlier in this chapter, you are now aware of a number of data-driven approaches to forms handling (and of some of the attendant risks).
If a forms handling machine is sufficiently flexible, then all it really needs is an adequate description of the form contents and a knowledge of its place in a workflow that specifies how each form is processed and what interactions take place with databases along the way. The work I have described in this area should have led you to expect a movement toward storing forms descriptions as relational data. To date, I have not found an existing package that does this. Others have developed libraries of varying degrees of sophistication, but nothing that would persuade me to leave the homegrown system I find so easy to use. Perhaps I will be able to incorporate database-driven forms handling in later versions.
One technology I am keeping an eye on, though, is XML Forms for Webware, a package under construction by Paul Boddie, whose name you read at the start of the chapter as the compiler of a web technology list. The package can be downloaded from http://thor.prohosting.com/~pboddie/. The documentation is much more detailed than most treatments of user interaction and addresses issues of state management as well as other development and maintenance techniques. Because Webware servlets are persistent, a servlet can include a description of the form it is processing as a part of its state. This makes it simpler to repeat the form with selective error messages if some inputs do not meet verification or validation criteria. That Paul chose Webware as his platform underlines the architecture's flexibility.