加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:27:12 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 # Initialize SimpleCache({'data':{'example':'example data'}}) # Getting instance c = SimpleCache.getInstance() c.set('re.reg_exp_compiled',r

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

 # 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 interface

Examples 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 g

def 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


以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读