Cache decorator

 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.core.cache import cache

def cached(cache_key='', timeout_seconds=1800):
    """Django cache decorator

    Example 1:
    class MenuItem(models.Model):
        @classmethod
        @cached('menu_root', 3600*24)
        def get_root(self):
            return MenuItem.objects.get(pk=1)

    Example 2:
    @cached(lambda u: 'user_privileges_%s' % u.username, 3600)
    def get_user_privileges(user):
        #...
    """
    def _cached(func):
        def do_cache(*args, **kws):
            if isinstance(cache_key, str):
                key = cache_key % locals()
            elif callable(cache_key):
                key = cache_key(*args, **kws)
            data = cache.get(key)
            if data: return data
            data = func(*args, **kws)
            cache.set(key, data, timeout_seconds)
            return data
        return do_cache
    return _cached

More like this

  1. Cache Decorator by ericmoritz 5 years, 4 months ago
  2. Stales Cache Class Method Decorator by amitu 5 years, 6 months ago
  3. Conditional cache decorator by alexisbellido 1 year, 8 months ago
  4. per-function cache decorator by nicois 6 years, 2 months ago
  5. Caching Decorator by spenczar 1 year, 12 months ago

Comments

(Forgotten your password?)