caching parsed templates

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.template import loader
from django.conf import settings


template_cache = {} 
original_get_template = loader.get_template
def cached_get_template(template_name):
    global template_cache
    t = template_cache.get(template_name,None)
    if not t or settings.DEBUG:
        template_cache[template_name] = t = original_get_template(template_name)
    return t
loader.get_template = cached_get_template

Comments

zgoda (on December 13, 2007):

Be aware that changes in template require server restart to become visible. Anyway, very nice feature.

#

alexdong (on May 8, 2008):

There is a little problem with this since Python 2.4's cache framework couldn't pickle a compiled template object. Without that, a production box will barely benefit from the cached template by fetching it from memcached.

An alternative is to patch the template loader source code with this ticket.

Alex from haokanbu.com

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.