Home > Articles > Programming > Python

This chapter is from the book

This chapter is from the book

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.


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
<LI>everybody run!

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 (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
 5 ctx = albatross.SimpleContext('.')
 6 templ = ctx.load_template('showenv.html')
 8 ctx.locals.environ = os.environ
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
 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')
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 (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>
 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>
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, 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 code—lightweight 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020