django orm的自动缓存和失效
django-cachebot的Python项目详细描述
django cachebot为django orm提供自动缓存和失效。
安装
easy_install django-cachebot或pip install django-cachebot
将cachebot添加到INSTALLED_APPS
将缓存后端设置为cachebots.backends中的一个后端,例如:
CACHES = { 'default': { 'BACKEND': 'cachebot.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } }
当前支持的后端为:
cachebot.backends.dummy.DummyCache cachebot.backends.memcached.MemcachedCache cachebot.backends.memcached.PyLibMCCache
如果要向模型添加缓存,模型的管理器必须是CacheBotManager或其子类,例如:
from django.db import models from cachebot.managers import CacheBotManager class Author(models.Model): name = models.CharField(max_length=50) objects = CacheBotManager() class BookManager(CacheBotManager): def for_author(self, name): return self.filter(author__name=name) class Book(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Author) objects = BookManager()
用法
默认情况下,对CacheBotManager的所有get查询都将被缓存:
photo = Photo.objects.get(user=user)
如果不需要此行为,请在定义管理器时调用CacheBotManager(cache_get=False),或在设置中更改此全局设置CACHEBOT_CACHE_GET=False。
对于更复杂的查询,假设您有一个类似于这样的查询,并且希望缓存它:
Photo.objects.filter(user=user, status=2)
只需像这样将.cache()添加到queryset链:
Photo.objects.cache().filter(user=user, status=2)
如果满足以下任一条件,此查询将无效:
1. One of the objects returned by the query is altered. 2. The user is altered. 3. A Photo is modified and has status = 2. 4. A Photo is modified and has user = user.
这个无效条件可能过于谨慎,因为我们不希望每次保存带有status = 2的照片时都使这个缓存失效。要微调无效条件,可以指定仅对某些字段无效。例如:
Photo.objects.cache('user').filter(user=user, status=2)
如果满足以下任一条件,此查询将无效:
1. One of the objects returned by the query is altered. 2. The user is altered. 3. A Photo is modified and has user = user.
django cachebot还可以处理与选择相关、正向关系和反向关系,即:
Photo.objects.select_related().cache('user').filter(user__username="david", status=2) Photo.objects.cache('user').filter(user__username="david", status=2) Photo.objects.cache('message__sender').filter(message__sender=user, status=2)
设置
- ^{tt13}$
- default: ^{tt14}$
- If set to ^{tt14}$, ^{tt6}$ will be called with ^{tt17}$ by default.
- ^{tt18}$
- default: (‘django_session’, ‘django_content_type’, ‘south_migrationhistory’)
- A list of tables that cachebot should ignore.
注意事项(重要!)
使用ManyRelatedManager添加/删除对象不会自动失效。您需要手动使这些查询无效,如so:
from cachebot.signals import invalidate_object user.friends.add(friend) invalidate_object(user) invalidate_object(friend)
count()查询将不会被缓存。
如果要对范围或排除查询中的字段失效,则当表中的任何内容发生更改时,这些查询将失效。例如,当用户表中的任何内容发生更改时,以下内容将无效:
Photo.objects.cache('user').filter(user__in=users, status=2) Photo.objects.cache('user').exclude(user=user, status=2)
您可能应该使用类似django-memcache-status的工具来检查缓存的状态。如果memcache溢出并开始删除键,那么查询可能不会失效。
.values\u list()尚未缓存。你应该这样做:
[photo['id'] for photo in Photo.objects.cache('user').filter(user=user).values('id')]
依赖关系
- Django 1.3
如果使用django 1.2,则可以使用django cachebot 0.3.1版