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. Yet another SQL debugging facility by miracle2k 6 years, 8 months ago
  2. Effective content caching for mass-load site using redirect feature by nnseva 2 years, 9 months ago
  3. enani by andisthermal 3 years, 3 months ago

Comments

zgoda (on December 13, 2007):

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

#

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.

#

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?)