1 ImportWeakref, Collections2 Import Time3 4 5 classLocalCache ():6NotFound =object ()7 8 classDict (Dict):9 def __del__(self):Ten Pass One A def __init__(self,maxlen=20): -Self.weak =Weakref. Weakkeydictionary () -Self.strong=collections.deque (maxlen=maxlen) the - @staticmethod - defnowtime (): - returnInt (time.time ()) + - defget (self, key): + #after each key-value pair, add a field expiration time A #first time to get expire= current time + expiration Time at #non-first time, expire judge whether the expiration, expired can be considered data not found - #data should be deleted after expiration -Value =self.weak.get (Key, Self.notfound) - #No expiration - if(Value is notself.notfound): -expire = Value[r'expire'] in #has expired - if(Self.nowtime () >expire): to returnSelf.notfound + Else: - returnvalue the #expired-returned not found * Else: $ returnSelf.notfoundPanax Notoginseng defSet (self,key,value): -self.weak[key]=strongref=localcache.dict (value) the self.strong.append (strongref) + A the fromFunctoolsImportWraps + - $ defFunccache (expire=1): $caches =LocalCache () - - def_wrappend (func): the @wraps (func) - def __wrapped(*args, * *Kwargs):Wuyi #calculates the key value of the cache theKey = str (func) + str (args) +Str (Kwargs) - Wuresult =caches.get (Key) - About if(Result islocalcache.notfound): $result = Func (*args, * *Kwargs) - -Caches.set (key, {R'result': result, R'expire': Expire +caches.nowtime ()}) - Aresult =caches.get (Key) + the returnresult - $ return __wrapped the the return_wrappend theF=funccache ()
View Code
Redis Custom Cache