標籤:eth app elf func 應該 sed opened self collect
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 pass11 12 def __init__(self,maxlen=20):13 self.weak = weakref.WeakKeyDictionary()14 self.strong=collections.deque(maxlen=maxlen)15 16 @staticmethod17 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.notFound32 else:33 return value34 # 到期了-返回沒有找到35 else:36 return self.notFound37 def set(self,key,value):38 self.weak[key]=strongRef=LocalCache.Dict(value)39 self.strong.append(strongRef)40 41 42 from functools import wraps43 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 result64 65 return __wrapped66 67 return _wrappend68 f=funcCache()
View Code
redis自訂緩衝