Wednesday, September 30, 2009

Python Cheetah Benchmark

With any web application, no matter what language it may be written in, templates need to be rendered. These are often HTML templates. If there were no templates, just static HTML files, what we would have is a static site as opposed to a web application. The dynamic aspects of the page are filled in by rendering a template. This is the most common approach for several reasons. Chiefly, the user interface is nicely separated from application logic. This, in turn, makes it easier for the user interfaces developers and designers to work without disrupting the logic they aren't concerned with. This also works vice-versa.

The Cheetah template rendering system, written for Python web applications, is a mature one. Cheetah provides a clean, elegant template syntax when compared to other Python template rendering systems. For instance, the syntax constructs are not represented as tags. This provides both flexibility and separation of concerns. Since tags aren't required, Cheetah can be used for templates other than HTML. Also, it is more obvious with Cheetah what is HTML markup and what is template markup.

Below is a very incomplete, sample of how to use Cheetah pragmatically. That is, it is very easy to plug into any potential Python system.
#Example; Timing Cheetah rendering.

#Do imports.
import timeit
from Cheetah.Template import Template

#Rendering test.
def render_cheetah():

#Cheetah template string.
template_str="""<html>
<head>
<title>$title</title>
</head>
<body>$body</body>
</html>"""

#The context supplied to the template; variable substitution.
context={"title":"Cheetah Test", "body":"Cheetah Test"}

#Initialize the Cheetah template object.
template_obj=Template(template_str, searchList=[context])

#Render the template.
str(template_obj)

#Main.
if __name__=="__main__":

#Run the test an print the results.
cheetah_timer=timeit.Timer("render_cheetah()",\
"from __main__ import render_cheetah")
print "Cheetah:",cheetah_timer.timeit(number=1000)

No comments :

Post a Comment