Attention Internet Explorer users: This site won't look like ass if you use a better browser. My site, my rules.

Template + Cache = Crazy Delicious

Here’s a simple class for a template tag that caches its output (with apologies to Chris Parnell and Andy Samberg):

from django.core import template
from django.core.cache import cache
from django.conf.settings import DEBUG

class CachedNode(template.Node):
    """
    Cached template node.

    Subclasses should define the methods
    get_cache_key() and get_content() instead of the
    standard render() method. Subclasses may also
    define the class attribute cache_timeout to
    override the default cache timeout of ten minutes.
    """

    cache_timeout = 600

    def render(self, context):
        if DEBUG:
            return self.get_content(context)
        key = self.get_cache_key(context)
        content = cache.get(key)
        if not content:
            content = self.get_content(context)
            cache.set(key, content, self.cache_timeout)
        return content

    def get_cache_key(self, context):
        raise NotImplementedError

    def get_content(self, context):
        raise NotImplementedError

Comments

phil

Jan. 31st, 2006

1:38 p.m.

2 questions:

- what's template ?
- the "cache" variable seems to come from nowhere ;)

Adrian Holovaty

Jan. 31st, 2006

1:46 p.m.

phil, I believe this code assumes these two imports:

from django.core import template
from django.core.cache import cache

phil

Jan. 31st, 2006

1:50 p.m.

Ok that's fine, Adrian ;)

Jacob

Jan. 31st, 2006

3:32 p.m.

Thanks, Phil - I've updated the code snippet to make that clear.

Ian Holsman

Jan. 31st, 2006

3:34 p.m.

any chance of checking that into the core?

Courtney

Feb. 1st, 2006

7:31 p.m.

Django is the best--true that--double true.

Thanks for the post. Keep the tips coming!

Your 2¢

Comment