具有高级失效能力和防止狗堆效应的缓存装饰器和django缓存后端
django-cache-utils的Python项目详细描述
django缓存实用程序提供了一些实用程序,使与缓存相关的工作更容易:
cached装饰器。它可以应用于函数、方法或类方法 可用于任何django缓存后端(内置或类似于 Django Newcache)。
支持精确参数集的细粒度失效(任何后端) 以及大容量缓存失效(仅使用group_backend)。缓存键是 因为它们是根据callable的全名和 然后对其进行消毒以使memcached高兴。
wrapped callable获取invalidate方法。用invalidate调用 与函数相同的参数,这些参数的缓存结果将是 无效。
group_backend。它是一个django memcached缓存后端,组为o(1) mintcache算法的失效能力、狗堆效应预防 和项目版本支持,允许Gracefull更新和多个Django 在同一个memcached实例上的项目。 长键(>;250)将自动截断并附加MD5哈希。
安装
pip install django-cache-utils
然后(可选):
# settings.py CACHE_BACKEND = 'cache_utils.group_backend://localhost:11211/'
用法
cacheddecorator可用于任何django缓存后端(内置或 第三方,如django newcache):
from cache_utils.decorators import cached @cached(60) def foo(x, y=0): print 'foo is called' return x+y foo(1,2) # foo is called foo(1,2) foo(5,6) # foo is called foo(5,6) foo.invalidate(1,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)
使用group_backend缓存装饰器支持批量o(1)无效:
from django.db import models from cache_utils.decorators import cached class CityManager(models.Manager): # cache a method result. 'self' parameter is ignored @cached(60*60*24, 'cities') def default(self): return self.active()[0] # cache a method result. 'self' parameter is ignored, args and # kwargs are used to construct cache key @cached(60*60*24, 'cities') def get(self, *args, **kwargs): return super(CityManager, self).get(*args, **kwargs) class City(models.Model): # ... field declarations objects = CityManager() # an example how to cache django model methods by instance id def has_offers(self): @cached(30) def offer_count(pk): return self.offer_set.count() return history_count(self.pk) > 0 # cache the function result based on passed parameter @cached(60*60*24, 'cities') def get_cities(slug) return City.objects.get(slug=slug) # cache for 'cities' group can be invalidated at once def invalidate_city(sender, **kwargs): cache.invalidate_group('cities') pre_delete.connect(invalidate_city, City) post_save.connect(invalidate_city, City)
注释
如果修饰函数返回,则不会绕过任何缓存。
django缓存实用程序使用memcached的2次读取来获取值if'group' 参数被传递给“cached”装饰符:
@cached(60) def foo(param) return .. @cached(60, 'my_group') def bar(param) return .. # 1 read from memcached value1 = foo(1) # 2 reads from memcached + ability to invalidate all values at once value2 = bar(1)
运行测试
cd test_project ./runtests.py