Method Caching

 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 6 years, 11 months ago
  2. Function decorator for caching function results in local memory by bikeshedder 1 year, 6 months ago
  3. Automatic Memoization Decorator by nikmolnar 1 year, 3 months ago
  4. Decorator that limits request methods by schinckel 4 years, 8 months ago
  5. ExtendibleModelAdminMixin by dokterbob 4 years, 5 months ago

Comments

(Forgotten your password?)