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

More like this

  1. server with debugging backdoor by teepark 4 years, 8 months ago
  2. IP Authorization Decorator with IP list by jansta 2 years, 3 months ago
  3. Test Server Thread by adamlofts 3 years, 11 months ago
  4. Apache X-sendfile with permissions checking by h0axify 1 year, 1 month ago
  5. SOAP web service with soaplib 0.9+ by wRAR 2 years, 7 months ago

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

#

fredz (on August 12, 2009):

Excellent !

I don't understand why this mecanism is not integrated in django.

The two only responses of django team about high load is to take care of sql queries and use cache, but there are dynamic sites (real estates for us) in which the cache is irrelevant (too many combinaisons of pages to use the cache). So bypassing the template parse for each query is a real optimisation (we have a 20-25% gain).

I don't really agree with the need of memcached, cause a site has a limited amount of templates, and it is more simple (and faster) to store the templates instance in a dict attached to each apache process, and reload the server when templates sources are modified.

Thank you.

#

fredz (on August 14, 2009):

See http://code.djangoproject.com/ticket/6262

#

mulianto (on April 7, 2012):

hi, is this snippet already in django distribute 1.3 ? i compare with per site cache and this one, the performance is faster with this snippet..

#

(Forgotten your password?)