1 import weakref, collections
2 import time
3
4
5 class LocalCache():
6 notFound = object()
7
8 class Dict(dict):
9 def __del__(self):
10 pass
11
12 def __init__(self,maxlen=20):
13 self.weak = weakref.WeakKeyDictionary()
14 self.strong=collections.deque(maxlen=maxlen)
15
16 @staticmethod
17 def nowTime():
18 return int(time.time())
19
20 def get(self, key):
21 # 每个键值对后面加个字段过期时间
22 # 第一次获取 expire=当前时间+过期时间
23 # 非第一次获取时候,expire判断是否过期,过期可认为数据没有找到
24 # 过期后应该删除数据
25 value = self.weak.get(key, self.notFound)
26 # 没有过期
27 if (value is not self.notFound):
28 expire = value[r'expire']
29 # 已经过期
30 if (self.nowTime() > expire):
31 return self.notFound
32 else:
33 return value
34 # 过期了-返回没有找到
35 else:
36 return self.notFound
37 def set(self,key,value):
38 self.weak[key]=strongRef=LocalCache.Dict(value)
39 self.strong.append(strongRef)
40
41
42 from functools import wraps
43
44
45 def funcCache(expire=1):
46 caches = LocalCache()
47
48 def _wrappend(func):
49 @wraps(func)
50 def __wrapped(*args, **kwargs):
51 # 计算出缓存的key值
52 key = str(func) + str(args) + str(kwargs)
53
54 result = caches.get(key)
55
56 if (result is LocalCache.notFound):
57 result = func(*args, **kwargs)
58
59 caches.set(key, {r'result': result, r'expire': expire + caches.nowTime()})
60
61 result = caches.get(key)
62
63 return result
64
65 return __wrapped
66
67 return _wrappend
68 f=funcCache()