我正在寻找一个Python缓存库,但目前还没有找到任何东西。我需要一个简单的类似
dict
的界面,我可以在其中设置密钥及其过期时间并将它们重新缓存。有点像:
cache.get(myfunction, duration=300)
如果存在的话,它将从缓存中给我该项目;如果不存在或已过期,则调用该函数并存储它。有谁知道这样的事情吗?
从 Python 3.2 开始,您可以使用 functools 库中的装饰器 @lru_cache。
这是一个“最近最少使用”缓存,因此其中的项目没有过期时间,但作为一种快速破解,它非常有用。
from functools import lru_cache
@lru_cache(maxsize=256)
def f(x):
return x*x
for x in range(20):
print f(x)
for x in range(20):
print f(x)
https://joblib.readthedocs.io 支持 Memoize 模式中的缓存功能。大多数情况下,这个想法是缓存计算量大的函数。
>>> from joblib import Memory
>>> mem = Memory(cachedir='/tmp/joblib')
>>> import numpy as np
>>> square = mem.cache(np.square)
>>>
>>> a = np.vander(np.arange(3)).astype(np.float)
>>> b = square(a)
________________________________________________________________________________
[Memory] Calling square...
square(array([[ 0., 0., 1.],
[ 1., 1., 1.],
[ 4., 2., 1.]]))
___________________________________________________________square - 0...s, 0.0min
>>> c = square(a)
您还可以做一些奇特的事情,例如在函数上使用 @memory.cache 装饰器。文档在这里:https://joblib.readthedocs.io/en/latest/ generated/joblib.Memory.html
class MemCache(dict):
def __init__(self, fn):
dict.__init__(self)
self.__fn = fn
def __getitem__(self, item):
if item not in self:
dict.__setitem__(self, item, self.__fn(item))
return dict.__getitem__(self, item)
mc = MemCache(lambda x: x*x)
for x in xrange(10):
print mc[x]
for x in xrange(10):
print mc[x]
它确实缺乏过期功能,但您可以通过在 MemCache c-tor 中指定特定规则来轻松扩展它。
希望代码足够不言自明,但如果不是,只需提及,该缓存正在传递一个转换函数作为其 c-tor 参数之一。它依次用于生成有关输入的缓存输出。
希望有帮助
旨在提供“人类缓存”
(不过好像还不太清楚)
项目页面的一些信息:
安装
用途:
import pylibmc
from cache import Cache
backend = pylibmc.Client(["127.0.0.1"])
cache = Cache(backend)
@cache("mykey")
def some_expensive_method():
sleep(10)
return 42
# writes 42 to the cache
some_expensive_method()
# reads 42 from the cache
some_expensive_method()
# re-calculates and writes 42 to the cache
some_expensive_method.refresh()
# get the cached value or throw an error
# (unless default= was passed to @cache(...))
some_expensive_method.cached()
cachebox 库。这比其他库要快得多(请参阅benchmark)并且支持 7 种缓存实现。 它有你想要的。这个图书馆称之为
VTTLCache
:
from cachebox import VTTLCache
import time
cache = VTTLCache(maxsize=256)
cache.insert(key, value, ttl=300)
assert cache.get(key) is not None
time.sleep(300)
assert cache.get(key) is None
keyring.set_password("service","jsonkey",json_res)
json_res= keyring.get_password("service","jsonkey")
json_res= keyring.core.delete_password("service","jsonkey")