| author | Simon Descarpentries <sid@sopinspace.com> |
| Tue, 06 May 2014 13:52:01 +0200 | |
| changeset 651 | 9bbc657f6837 |
| parent 349 | 8d1ce1bda109 |
| permissions | -rw-r--r-- |
| 0 | 1 |
from django.core.cache import cache |
| 261 | 2 |
from hashlib import sha1 |
|
349
8d1ce1bda109
workspace in parameter for memoize
Production Moz <dev@sopinspace.com>
parents:
261
diff
changeset
|
3 |
from django.conf import settings |
| 0 | 4 |
|
5 |
# adapted [to django] from http://code.activestate.com/recipes/325205/ |
|
6 |
def dj_memoize(f): |
|
7 |
def g(*args, **kwargs): |
|
|
349
8d1ce1bda109
workspace in parameter for memoize
Production Moz <dev@sopinspace.com>
parents:
261
diff
changeset
|
8 |
key = sha1( str((settings.SITE_URL, f.__name__, f, tuple(args), frozenset(kwargs.items())) )).hexdigest() |
| 0 | 9 |
val = cache.get(key) |
10 |
if not val: |
|
11 |
val = f(*args, **kwargs) |
|
12 |
cache.set(key,val) |
|
13 |
return val |
|
14 |
return g |
|
15 |
||
16 |
||
17 |
||
18 |
# adapted from http://code.activestate.com/recipes/496879/ |
|
19 |
# decorator with LRU policy |
|
20 |
||
21 |
# changed : |
|
22 |
# - default limit is 100 |
|
23 |
# - store sha1 of key (shorter) |
|
24 |
import cPickle, hashlib |
|
25 |
||
26 |
def memoize(function, limit=100): |
|
27 |
if isinstance(function, int): |
|
28 |
def memoize_wrapper(f): |
|
29 |
return memoize(f, function) |
|
30 |
||
31 |
return memoize_wrapper |
|
32 |
||
33 |
dict = {} |
|
34 |
list = [] |
|
35 |
def memoize_wrapper(*args, **kwargs): |
|
36 |
key = hashlib.sha1(cPickle.dumps((args, kwargs))).digest() |
|
37 |
try: |
|
38 |
list.append(list.pop(list.index(key))) |
|
39 |
except ValueError: |
|
40 |
dict[key] = function(*args, **kwargs) |
|
41 |
list.append(key) |
|
42 |
if limit is not None and len(list) > limit: |
|
43 |
del dict[list.pop(0)] |
|
44 |
||
45 |
return dict[key] |
|
46 |
||
47 |
memoize_wrapper._memoize_dict = dict |
|
48 |
memoize_wrapper._memoize_list = list |
|
49 |
memoize_wrapper._memoize_limit = limit |
|
50 |
memoize_wrapper._memoize_origfunc = function |
|
51 |
memoize_wrapper.func_name = function.func_name |
|
52 |
return memoize_wrapper |