Login

Cached template filters

Author:
coleifer
Posted:
May 8, 2010
Language:
Python
Version:
1.1
Tags:
template cache
Score:
1 (after 1 ratings)

Say you'd like to cache one of your template filters. This decorator acts sort of like memoize, caching a result set based on the arguments passed in (which are used as the cache key).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.conf import settings
from django.db.models.query import QuerySet
from django.utils.cache import cache
from django.utils.hashcompat import md5_constructor

def stringify_object(obj):
    if isinstance(obj, QuerySet):
        return obj.query.as_sql()
    return unicode(obj)

def key_from_args(*args, **kwargs):
    strings = []
    for arg in args:
        strings.append(stringify_object(arg))
    for k,v in kwargs.items():
        strings.append('%s=%s' % (k, stringify_object(v)))
    return md5_constructor(''.join(strings).hexdigest())

def cached_filter(func, timeout=300):
    def inner(*args, **kwargs):
        if settings.DEBUG:
            return func(*args, **kwargs)
        cache_key = key_from_args(*args, **kwargs)
        result = cache.get(cache_key)
        if not result:
            result = func(*args, **kwargs)
            cache.set(cache_key, result, timeout)
        return result
    inner._decorated_function = func
    return inner

More like this

  1. ImageMagick commands from Django Templates by cogat 6 years ago
  2. Filter by first letter inclusion tag by slafs 4 years, 11 months ago
  3. Extended db cache backend with 'filter() / LIKE' support (and now scheduled cache clean!) by sleepycal 5 years, 3 months ago
  4. Parsed RSS into template var by bram 6 years, 10 months ago
  5. A few jinja2 filters like django ones by brondsem 6 years, 1 month ago

Comments

Please login first before commenting.