django - 使特定缓存无效

标签 django django-cache

我在基本模板中有缓存标记:

{% cache 100000 categories %}
    Categories output
{% endcache %}

当我通过 Django 管理添加新类别时,我想使此缓存无效:

class CategoriesAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super(CategoriesAdmin, self).save_model(request, obj, form, change)

        cache.delete('categories')

但是缓存仍然有效!怎么了?

最佳答案

这是因为实际的键不是“类别”,而是由 Django 使用以下内容动态构建的键:

args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on]))
cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())

参见:https://code.djangoproject.com/browser/django/tags/releases/1.3.1/django/templatetags/cache.py

一般来说, key 的格式为:template.cache.categories.[hexdigest]。所以棘手的部分是弄清楚十六进制摘要部分。

我发现了以下Django snippet (在评论中),看起来它应该仍然有效(从 2009 年开始):

from django.core.cache import cache
from django.utils.hashcompat import md5_constructor
from django.utils.http import urlquote

def invalidate_template_cache(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
    cache.delete(cache_key)

由于您没有将任何变量传递给模板标记,因此您可以仅使用:invalidate_template_cache('categories') 来调用它。否则,您需要传入模板标记变化的所有变量的列表作为第二个参数。

关于django - 使特定缓存无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9568004/

相关文章:

python - 如何在 django admin 中添加编辑和删除按钮

python - django admin 不显示值

python - Django:部署到 ElasticBeanstalk myapp.settings 上导入错误

django rest 框架不接受 blob 图片文件(不允许文件扩展名 “”)

python - 属性错误 : 'RegexURLResolver' object has no attribute '_urlconf_module'

Django:如何处理 Ajax 请求不同 View 中的缓存?

python - 如何使 Django 数据库缓存的条目过期?

python - 如何在 Django 中以编程方式呈现和缓存 View ?

django 缓存 REST API Urls 问题