Login

Cachable Class Method Decorator

Author:
amitu
Posted:
October 13, 2008
Language:
Python
Version:
1.0
Tags:
cache decorator
Score:
4 (after 4 ratings)

This decorator does automatic key generation and simplifies caching. Can be used with any class, not just model subclasses.

Also see Stales 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
from django.core.cache import cache

def cacheable(cache_key, timeout=3600):
    def paramed_decorator(func):
        def decorated(self):
            key = cache_key % self.__dict__
            res = cache.get(key)
            if res == None:
                res = func(self)
                cache.set(key, res, timeout)
            return res
        decorated.__doc__ = func.__doc__
        decorated.__dict__ = func.__dict__
        return decorated 
    return paramed_decorator

# Usage:

class SomeClass(models.Model):
    # fields [id, name etc]

    @cacheable("SomeClass_get_some_result_%(id)s")
    def get_some_result(self):
        # do some heavy calculations
        return heavy_calculations()

    @cacheable("SomeClass_get_something_else_%(name)s")
        return something_else_calculator(self)

More like this

  1. Stales Cache Class Method Decorator by amitu 6 years, 7 months ago
  2. Cache Decorator by ericmoritz 6 years, 5 months ago
  3. Conditional cache decorator by alexisbellido 2 years, 9 months ago
  4. Method Caching by bryanhelmig 3 years, 11 months ago
  5. Decorator cache handler per view by guicifuentes 6 years, 8 months ago

Comments

seandong (on May 25, 2009):

May be cache value is None,that the code below res = cache.get(key) if res == None:

should change to:

if not cache.has_key(key): .... else: return cache.get(key)

#

Please login first before commenting.