Python实现简单的缓存和缓存decorator

Python实现简单的缓存和缓存decorator,第1张

概述Python实现简单的缓存和缓存decorator

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

 # Initialize    SimpleCache({'data':{'example':'example data'}})    # Getting instance    c = SimpleCache.getInstance()    c.set('re.reg_exp_compiled',re.compile(r'\W*'))    reg_exp = c.get('re.reg_exp_compiled',default=re.compile(r'\W*'))    # --------------------------------------------------------------    c = SimpleCache.getInstance()    reg_exp = c.getset('re.reg_exp_compiled',re.compile(r'\W*'))    # --------------------------------------------------------------        @scache    def func1():        return 'OK'

实现
__author__ = "Andrey Nikishaev"__copyright__ = "copyright 2010,http://creotiv.in.ua"__license__ = "GPL"__version__ = "0.3"__maintainer__ = "Andrey Nikishaev"__email__ = "[email protected]"__status__ = "Production""""Simple local cache.It saves local data in singleton dictionary with convenIEnt interfaceExamples of use:    # Initialize    SimpleCache({'data':{'example':'example data'}})    # Getting instance    c = SimpleCache.getInstance()    c.set('re.reg_exp_compiled',default=re.compile(r'\W*'))or    c = SimpleCache.getInstance()    reg_exp = c.getset('re.reg_exp_compiled',re.compile(r'\W*'))or    @scache    def func1():        return 'OK'"""class SimpleCache(dict):    def __new__(cls,*args):        if not hasattr(cls,'_instance'):            cls._instance = dict.__new__(cls)        else:            raise Exception('SimpleCache already initialized')        return cls._instance    @classmethod    def getInstance(cls):        if not hasattr(cls,'_instance'):            cls._instance = dict.__new__(cls)        return cls._instance    def get(self,name,default=None):        """Multilevel get function.        Code:                Config().get('opt.opt_level2.key','default_value')        """        if not name:             return default        levels = name.split('.')        data = self                    for level in levels:            try:                            data = data[level]            except:                return default        return data    def set(self,value):        """Multilevel set function        Code:                Config().set('opt.opt_level2.key','default_value')        """        levels = name.split('.')        arr = self                for name in levels[:-1]:            if not arr.has_key(name):                         arr[name] = {}               arr = arr[name]        arr[levels[-1]] = value    def getset(self,value):        """Get cache,if not exists set it and return set value        Code:                Config().getset('opt.opt_level2.key','default_value')        """        g = self.get(name)        if not g:            g = value            self.set(name,g)        return gdef scache(func):    def wrapper(*args,**kwargs):        cache = SimpleCache.getInstance()        fn = "scache." + func.__module__ + func.__class__.__name__ + \             func.__name__ + str(args) + str(kwargs)                val = cache.get(fn)        if not val:            res = func(*args,**kwargs)            cache.set(fn,res)            return res        return val    return wrapper


以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的Python实现简单的缓存和缓存decorator全部内容,希望文章能够帮你解决Python实现简单的缓存和缓存decorator所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1199207.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存