Login

Method Caching

Author:
bryanhelmig
Posted:
July 1, 2011
Language:
Python
Version:
1.3
Tags:
memcache cache decorator memcached decorators caching
Score:
2 (after 2 ratings)

A very simple decorator that caches both on-class and in memcached:

@method_cache(3600)
def some_intensive_method(self):
    return # do intensive stuff`

Alternatively, if you just want to keep it per request and forgo memcaching, just do:

@method_cache()
def some_intensive_method(self):
    return # do intensive stuff`
 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
31
32
33
34
35
36
37
38
39
40
def method_cache(seconds=0):
    """
    A `seconds` value of `0` means that we will not memcache it.
    
    If a result is cached on instance, return that first.  If that fails, check 
    memcached. If all else fails, hit the db and cache on instance and in memcache. 
    
    ** NOTE: Methods that return None are always "recached".
    """
    
    from hashlib import sha224
    from django.core.cache import cache
    
    def inner_cache(method):
        
        def x(instance, *args, **kwargs):
            key = sha224(str(method.__module__) + str(method.__name__) + \
                str(instance.id) + str(args) + str(kwargs)).hexdigest()
            
            
            if hasattr(instance, key):
                # has on class cache, return that
                result = getattr(instance, key)
            else:
                result = cache.get(key)
                
                if result is None:
                    # all caches failed, call the actual method
                    result = method(instance, *args, **kwargs)
                    
                    # save to memcache and class attr
                    if seconds and isinstance(seconds, int):
                        cache.set(key, result, seconds)
                    setattr(instance, key, result)
            
            return result
        
        return x
    
    return inner_cache

More like this

  1. template + cache = crazy delicious by jacobian 8 years, 2 months ago
  2. Function decorator for caching function results in local memory by bikeshedder 2 years, 9 months ago
  3. Automatic Memoization Decorator by nikmolnar 2 years, 6 months ago
  4. Decorator that limits request methods by schinckel 5 years, 11 months ago
  5. ExtendibleModelAdminMixin by dokterbob 5 years, 7 months ago

Comments

Please login first before commenting.