跳转到主要内容

缓存/限流函数调用的实用工具。

项目描述

功能

  • 优雅的错误处理(可以回退到缓存值)

  • 在后台计算结果(需要Celery

  • 可读的持续时间字符串(‘1天’86400

  • 正确处理 None

  • 按调用无效化

安装

  1. pip install django-throttleandcache

  2. 在您的 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:此参数指定错误应如何处理。如果gracefulTrue且您的函数引发错误,throttleandcache将记录错误并返回缓存值。如果不存在缓存值,则引发原始错误。

  • background:指定新值应在后台(使用Celery)计算。

项目详细信息


下载文件

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

源分发

django-throttleandcache-2.1.0.tar.gz (7.9 kB 查看散列)

上传时间