[英]Expiring a view-cache in Django 1.3.1
我正在尝试使模型的post_save
(通过https://docs.djangoproject.com/en/1.3/topics/cache/?from=olddocs#the-per-view-cache设置)上的视图级缓存过期)。 我做了一些谷歌搜索,然后在SO上找到了这个答案: 在Django中终止视图缓存? 但这对我不起作用。
我在freenode上的#django会议室中问了一下,共识是这可能是由于1.3中最近进行了缓存更改
有人对我如何清除为get_absolute_url()
锁定的模型的缓存条目有任何想法吗?
为ilvar欢呼为我指明了正确的方向。 我的实现如下。 我创建了一个名为cache_key
的属性,并将post_save接收器添加到了模型的子类上,这些子类在更新后需要清除其视图级缓存。 随时欢迎提出改进建议!
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save
from django.http import HttpRequest
from django.utils.cache import _generate_cache_header_key
from someapp.models import BaseModelofThisClass
class SomeModel(BaseModelofThisClass):
...
@property
def cache_key(self):
# Create a fake request object
request = HttpRequest()
# Set the request method
request.method = "GET"
# Set the request path to be this object's permalink.
request.path = self.get_absolute_url()
# Grab the key prefix (if it exists) from settings
key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
# Generate this object's cache key using django's key generator
key = _generate_cache_header_key(key_prefix, request)
# This is a bit hacky but necessary as I don't know how to do it
# properly otherwise. While generating a cache header key, django
# uses the language of the HttpRequest() object as part of the
# string. The fake request object, by default, uses
# settings.LANGUAGE_CODE as it's language (in my case, 'en-us')
# while the true request objects that are used in building views
# use settings.LANGUAGES ('en'). Instead of replacing the segment
# of the string after the fact it would be far better create a more
# closely mirrored HttpRequest() object prior to passing it to
# _generate_cache_header_key().
key = key.replace(settings.LANGUAGE_CODE, settings.LANGUAGES[settings.DEFAULT_LANGUAGE][0])
return key
@receiver(post_save)
def clear_cache_for_this_item(sender, instance, **kwargs):
# If this is a sub-class of another model
if sender not in BaseModelofThisClass.__subclasses__():
return
else:
cache.delete(instance.cache_key)
Django的缓存中间件正在使用它来生成请求的缓存键。 因此,您可以使用所需的路径发出假request
并获取缓存密钥。 然后只需将其从缓存中删除。
PS cache_page
装饰器也使用该中间件,因此它应该以相同的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.