简单对象/方法结果缓存具有可选的持久缓存。支持内存文件或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

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何使用“Wed,01 Jul 2015 17:32:41 EDT”解析字符串   java Storm apache升级(1.0.0到2.0.0)   java类驻留在不同的目录中,而不是包指定的目录。为什么?   将Java中的图像缩放到非常小的维度   java如何通过子文档从自定义方面访问ElasticSearch parentdoc字段   java如何在RationalSoftwareArchitect中使用findbugs?   Java中的事件提升处理   java值被添加到arrayList的所有索引中,而不是在“”时添加到最后一个索引中。正在使用arraylist的add()方法   JFrame中的java JPanel派生类   java如何用循环和异步方法模拟类   java Android阻止可绘制背景超出视图范围   为客户排序Java阵列   java Apache poi如何将工作表设置为枚举位置值属性?   java Rhino在使用自定义类参数调用javascript函数时出错   java格式化日期从年月日到年月日   spring如何修复java。lang.illegalargumentexception在此特定场景中是否尝试创建具有null实体的合并事件?   java如何创建更好的对象