简单对象/方法结果缓存具有可选的持久缓存。支持内存文件或redis作为存储
object_cacher的Python项目详细描述
对象的简单缓存。将对象的副本存储在内存中(或pickle存储在文件中),并返回该对象的副本。函数参数这是一个缓存键。
>>> from object_cacher import ObjectCacher >>> @ObjectCacher(timeout=5) ... def test(*args): ... print ('Real call') ... return args ... >>> test(1,2,3) Real call (1, 2, 3)>>> test(1,2,3) (1, 2, 3)>>> test(1,2,3,4) Real call (1, 2, 3, 4)>>> test(1,2,3,4) ... (1, 2, 3, 4)
对硬函数或方法的结果进行缓存。 例如,您有一个远程restful api,其中包含许多字典。您可以缓存它:
>>> from urllib import urlopen >>> from object_cacher import ObjectCacher >>> @ObjectCacher(timeout=60) ... def get_api(): ... print "This real call" ... return urlopen('https://api.github.com/').read() ... >>> get_api() This real call '{"current_user_url":"https://api.github.com/user", ...' >>> get_api() '{"current_user_url":"https://api.github.com/user", ...'
因此,您只发出了一次http请求。
对于方法,您可以这样使用:
>>> from urllib import urlopen >>> from object_cacher import ObjectCacher >>> class API(object): ... @ObjectCacher(timeout=60, ignore_self=True) ... def get_methods(self): ... print "Real call" ... return urlopen('https://api.github.com/').read() ... >>> a = API() >>> a.get_methods() Real call '{"current_user_url":"https://api.github.com/user", ...' >>> b = API() >>> b.get_methods() '{"current_user_url":"https://api.github.com/user", ...'
如果设置了ignore_self参数,缓存将由所有实例共享。否则将拆分实例的缓存。
也可以使用持久缓存。 “objectPersistentCacher”类装饰器生成基于文件的pickle序列化缓存存储。 如果要在重新运行后保留缓存,则必须确定缓存ID:
>>> from urllib import urlopen >>> from object_cacher import ObjectCacher >>> class API(object): ... @ObjectPersistentCacher(timeout=60, ignore_self=True, oid='com.github.api.listofmethods') ... def get_methods(self): ... print "Real call" ... return urlopen('https://api.github.com/').read() ... >>> a = API() >>> a.get_methods() Real call '{"current_user_url":"https://api.github.com/user", ...' >>> b = API() >>> b.get_methods() '{"current_user_url":"https://api.github.com/user", ...'
这就是重新运行后保留缓存。
您可以通过更改“cache-dir”类属性来更改objectpersistentcacher的缓存目录。
>>> ObjectPersistentCacher.CACHE_DIR = '/var/tmp/my_cache'
安装
您可以从pypi安装
pip install object_cacher
或手动操作
python setup.py install