Simon Brunning pointed me to this resource for web programming in python and recommended Quixote or PHP from the Webware project. Of course, in the typical response of programmers everywhere I decided to hack something together myself instead.
In my defense I can only say that my requirements are very, very simple, and I wanted an opportunity to expand my python "skills". The system I came up with is a basic version of Java Server Pages (very basic). A template is just an HTML page with <#= and #> around any python expressions. The values of the expressions are substituted into the page at runtime. All variables used by the template are provided as members of a dictionary called v. For example:
<h1>Written by <#= v["author"] #></h1>
The actual template is created from the html page by converting the page into the source code for a python function, compiling the function, and then executing it passing in the dictionary that provides the variable values. The generated function is cached and reused if the source file hasn't changed since the function was generated. Templates are of course represented as objects so creating and using one looks like:
t = Template("test.html")
t.execute({"author":"Alex", "date":"October 2002"})
Extending this would probably involve adding a TemplateFactory that cached templates. Adding support for compound python statements while, for etc. is compilcated by python's use of indentation to mark scope. If I ever need this I'll probably have to go with some sort of END_BLOCK or DEDENT marker to end up with:
<ul> <# for item in v["lines"]: #> <li><#= item #></li> <# END_BLOCK #> </ul>
Anyway, here's the source code, and here it is syntax highlighted for viewing.
Posted by Alex at October 24, 2002 10:00 PM