Template + Cache = Crazy Delicious
I wrote this post in 2006, more than 18 years ago.
It may be very out of date, partially or totally incorrect. I may even no longer agree
with this, or might approach things differently if I wrote this post today. I rarely edit
posts after writing them, but if I have there'll be a note at the bottom about what
I changed and why. If something in this post is actively harmful or dangerous please get in
touch and I'll fix it.
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