Jinja2 Rocks!

Jinja2 is an awesome templating system! I've always been happy with the builtin templating framework in Django until about a week ago when I needed to render large amounts of tabular data. Then the Django templating system more or less breaks down because the rendering takes over 2 - 300 milliseconds which is to much time.

My first solution was to aggressively cache rendered pages using the cache middleware. Unfortunately that makes it hard to keep data changes in sync with what visitors see on the site. Plus, the first time the page is accessed is still slow.

The real solution was to throw out the old Django templates and start to learn Jinja2. It's not done yet, but I'm getting there. Meanwhile, here is a performance test that shows how much superior Jinja2 is:

# First the Jinja2 variant from jinja2 import Template from time import time t = Template(''' {% for obj in objs %} <tr> <td>{{ obj.x }}</td> <td>{{ obj.y }}</td> <td>{{ obj.x }}</td> <td>{{ obj.y }}</td> </tr> {% endfor %} ''') class O: x = 3.4 y = 2.5 objs = [O() for x in range(350)] s = time() for x in range(10): print t.render(objs = objs) print (time() - s) / 10.0 # Then Django templates. from django.template import Context, Template from time import time t = Template(''' {% for obj in objs %} <tr> <td>{{ obj.x }}</td> <td>{{ obj.y }}</td> <td>{{ obj.x }}</td> <td>{{ obj.y }}</td> </tr> {% endfor %} ''') class O: x = 3.4 y = 2.5 objs = [O() for x in range(350)] c = Context({'objs' : objs}) s = time() for x in range(10): t.render(c) print (time() - s) / 10.0

Inga kommentarer:

Bloggarkiv