per-function 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
from hashlib import sha1
from django.core.cache import cache as _djcache
def cache(seconds = 900):
    """
        Cache the result of a function call for the specified number of seconds, 
        using Django's caching mechanism.
        Assumes that the function never returns None (as the cache returns None to indicate a miss), and that the function's result only depends on its parameters.
        Note that the ordering of parameters is important. e.g. myFunction(x = 1, y = 2), myFunction(y = 2, x = 1), and myFunction(1,2) will each be cached separately. 

        Usage:

        @cache(600)
        def myExpensiveMethod(parm1, parm2, parm3):
            ....
            return expensiveResult
`
    """
    def doCache(f):
        def x(*args, **kwargs):
                key = sha1(str(f.__module__) + str(f.__name__) + str(args) + str(kwargs)).hexdigest()
                result = _djcache.get(key)
                if result is None:
                    result = f(*args, **kwargs)
                    _djcache.set(key, result, seconds)
                return result
        return x
    return doCache

More like this

  1. Caching Decorator by spenczar 1 year, 12 months ago
  2. Cache Decorator by ericmoritz 5 years, 4 months ago
  3. Cache decorator by xyb 6 years, 4 months ago
  4. ached decorator for functions by pawnhearts 4 years, 3 months ago
  5. Function cache decorator by bradbeattie 1 year, 5 months ago

Comments

(Forgotten your password?)