缓存/限流函数调用的实用工具。
项目描述
功能
优雅的错误处理(可以回退到缓存值)
在后台计算结果(需要Celery)
可读的持续时间字符串(‘1天’ 与 86400)
正确处理 None
按调用无效化
安装
pip install django-throttleandcache
在您的 settings.py 文件中设置缓存后端。
用法
from throttleandcache import cache
# Cache the result of my_function for 3 seconds.
@cache('3s')
def my_function():
return 'whatever'
如果您多次调用具有相同参数的函数,结果将从缓存中获取。为了使该调用的缓存失效,请使用相同参数调用 my_function.invalidate()
my_function()
my_function() # Result pulled from cache
my_function.invalidate()
my_function() # Not from cache
如果已安装Celery,您可以从请求/响应周期中删除新值的计算
@cache('3s', background=True)
def my_function():
return 'whatever'
请注意,在缓存较冷的情况下,值仍将同步计算。在新的值正在计算时,可能会使用旧值。
请记住,在多个实例上调用相同的方法意味着每个调用都将有一个不同的第一个位置参数(self)
class A(object):
@cache('100s')
def my_function(self):
print 'The method is being executed!'
instance_1 = A()
instance_2 = A()
instance_1.my_function() # The original method will be invoked
instance_2.my_function() # Different "self" argument, so the method is invoked again.
如果您希望在所有实例间缓存结果,请使用 @cacheforclass。
缓存装饰器的第一个参数是超时,可以以秒数或字符串的形式提供。由于字符串包含单位,它们可以使您的代码更易于阅读。一些示例是 ‘2s’、‘3m’、‘3m 2s’ 和 ‘3 minutes, 2 seconds’。
缓存装饰器还接受以下(可选)关键字参数
using: 指定要使用的缓存。
key_prefix:用于缓存键前缀的字符串。
- key_func:用于派生缓存键的函数。此函数将被传递fn、*args和**kwargs。
- graceful:此参数指定错误应如何处理。如果graceful为True且您的函数引发错误,throttleandcache将记录错误并返回缓存值。如果不存在缓存值,则引发原始错误。
- background:指定新值应在后台(使用Celery)计算。
项目详细信息
关闭
django-throttleandcache-2.1.0.tar.gz的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 9b67befe3d05f5b5c434c7d4b38f0abe75d034a93a47edbc752d08fc397587bf |
|
MD5 | d468f077b04a7181e0b1a0fb1e55a0ec |
|
BLAKE2b-256 | 02b2f98913e85acd85a4581f9a5e21ebc93afdcc757fd032d393de2f4a11d26a |