Page tree
Skip to end of metadata
Go to start of metadata

采用了 repoze.lru , 见github, 见文档

# 普通的cache
cache = repoze.lru.LRUCache(1000)
cache.put(key, val)
cache.get(key, None)
 
# 带过期的cache
expired_cache = repoze.lru.ExpiringLRUCache(1000, 600)
expired_cache.put(key, val, timeout)
expired_cache.get(key, None)


支持 lru_cache 修饰器:

def test_func():
    pass
 
cache_func = lru_cache(1000, timeout=86400)(test_func)


查看了lru_cache的源码, 发现其cache在内存存储采用的dict, 而这也意味着key必需hashable, 如果cache时候type(key) 为 list 或 dict这些不可哈希的类型,则会报错.

实际应用中,我们可以自己扩展一下 lru_cache 修饰器:

"""lru_cache 修饰器
 
repoze.lru默认的lru_cache decorator只能修饰参数可哈希的函数,
type(arg) in [list, dict] will raise TyperError: unhashable type: xxxx
"""
def lru_cache(prefix=''):
    def lru_cache_wrap(method):
        def wrapper(self, *args):
            key = prefix + json.dumps(args)
            val = self.lru_cache.get(key)
            if val is None:
                val = method(self, *args)
                self.lru_cache.put(key, val)
 
            return val
        return wrapper
    return lru_cache_wrap


  • No labels
Write a comment...