如何在Django中显式重置模板片段缓存?

dan*_*007 3 django django-templates django-cache python-memcached

我正在为我的Django应用程序使用Memcache.

在Django中,开发人员可以使用模板片段缓存来仅缓存模板的一部分.https://docs.djangoproject.com/en/dev/topics/cache/#template-fragment-caching

我想知道是否有一种方法可以在views.py中明确更改模板片段缓存部分的值.例如,除了模板片段缓存之外,可以使用类似于cache.set("sidebar","new value")的方法吗?

谢谢您的帮助.

mip*_*adi 6

从理论上讲,是的.首先必须使用Django使用的相同模式创建模板缓存密钥,这可以通过以下代码片段完成:

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

def template_cache_key(fragment_name, *vary_on):
    """Builds a cache key for a template fragment.

    This is shamelessly stolen from Django core.
    """
    base_cache_key = "template.cache.%s" % fragment_name
    args = md5_constructor(u":".join([urlquote(var) for var in vary_on]))
    return "%s.%s" % (base_cache_key, args.hexdigest())
Run Code Online (Sandbox Code Playgroud)

然后你可以做一些cache.set(template_cache_key(sidebar), 'new content')改变它的事情.

但是,在视图中这样做有点难看.当模型改变时,设置保存后信号和使缓存条目失效更有意义.

上面的代码片段适用于Django 1.2及以下版本.我不确定Django 1.3+的兼容性; django/templatetags/cache.py将有最新的信息.

对于Django 1.7,django/core/cache/utils.py具有可用的功能.

  • 刚刚发现,有一个记录的功能:https://docs.djangoproject.com/en/dev/topics/cache/#django.core.cache.utils.make_template_fragment_key (2认同)