Redis Custom Cache

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.