django缓存decorator+invalidate函数

django-cache-utils2的Python项目详细描述


django-cache-utils2提供cacheddecorator和invalidate函数。

安装

pip install django-cache-utils2

用法

from cache_utils2 import cached, invalidate

@cached(60)
def foo(x, y=0):
    print 'foo is called'
    return x+y

foo(1, 2) # foo is called
foo(1, y=2)
foo(5, 6) # foo is called
foo(5, 6)
invalidate(foo, {'x': 1, 'y': 2})
foo(1, 2) # foo is called
foo(5, 6)
foo(x=2) # foo is called
foo(x=2)

class Foo(object):
    @cached(60)
    def foo(self, x, y):
        print "foo is called"
        return x+y

obj = Foo()
obj.foo(1,2) # foo is called
obj.foo(1,2)

invalidate(Foo.foo, {'x': 1, 'y': 2})
obj.foo(1,2) # foo is called

django示例

from django.db import models
from cache_utils2 import cached, invalidate

class CityManager(models.Manager):

    # cache a method result. 'self' parameter is ignored
    @cached(60*60*24)
    def default(self):
        return self.active()[0]

    # cache a method result. 'self' parameter is ignored, args and
    # kwargs are used to construct the cache key
    @cached(60*60*24)
    def get(self, *args, **kwargs):
        return super(CityManager, self).get(*args, **kwargs)


class City(models.Model):
    # ... field declarations

    objects = CityManager()

    # cache django model instance method result by instance pk
    @cached(30, vary='self.pk')
    def has_offers(self):
        return self.offer_set.count() > 0

# invalidation of model methods
invalidate(City.has_offers, {'self.pk': 1}

注释

如果修饰函数返回cache_utils2.NO_CACHE缓存将被忽略。

运行测试

获取源代码并运行runtests.py

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

推荐PyPI第三方库


热门话题
linux Java线程创建跟踪   java可以让UNMIDEANER考虑文档过滤吗?   获取元素的java数组   java在ArrayList中搜索字符串并返回另一个关联字符串   java将现有私钥导入BKS密钥库   java proguard死代码分析给出了私有字段的假阳性   Java Web框架,用于新项目   java Gson:指定类或字段的命名策略   递归Java:保存递归本地计数器的值   java jfree图表集在图表中显示范围x值   Java:可以比较一个类吗对象是否具有泛型类型参数?   java JMS单个会话可以有多个MessageProducer吗?   java如何比较100条字符串记录,这些记录应该有3个值,即true、False或null   打开GUI实例的java检查   java如何重构具有多个切换情况的应用程序?   java如何更新Ubuntu上已经安装的IntelliJ IDEA?   java如何避免更改存档中文件的文件属性?