跳转到主要内容

具有可选持久缓存的简单对象/方法结果缓存。支持内存文件或Redis作为存储

项目描述

为您的对象提供简单的缓存。在内存中存储对象的副本(或将它们序列化到文件中)并返回该对象的副本。函数参数是缓存键。

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

项目详情


下载文件

下载适合您的平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源分布

object-cacher-0.3.1.tar.gz (3.8 kB 查看散列)

上传时间:

支持者