Login

Method Caching

Author:
bryanhelmig
Posted:
July 1, 2011
Language:
Python
Version:
1.3
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 tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.