重置Django缓存模板加载器的缓存

Dat*_*eed 9 django memcached django-templates

Django 1.2引入了一个新的模板加载器,它将数据存储在cache(django.template.loaders.cached.Loader)中.

不幸的是,我没有找到有关缓存如何失效以及何时以及如何重置的任何信息.

我想在我的服务器上使用它,但我不确定,它会在django restart上重置(这对我来说已经足够了).

cor*_*ror 6

由于模板加载器系统已被重构,此处编写的现有解决方案在 Django 1.9 左右就崩溃了。如果您尝试使用导入的代码template_source_loaders但导入失败,请尝试以下操作:

from django.template.loader import engines

for engine in engines.all():
    engine.engine.template_loaders[0].reset()
Run Code Online (Sandbox Code Playgroud)

此代码假设您的TEMPLATES设置使用默认'loaders'选项,或仅使用单个django.template.loaders.cached.Loader.


小智 5

from django.template.loader import template_source_loaders

def reset_template_cache():
    if not template_source_loaders:
        return

    for loader in template_source_loaders:
        loader.reset()
Run Code Online (Sandbox Code Playgroud)

你去了:)


adi*_*ieu 4

通过深入研究 django 的源代码,您可以发现当前服务器实例的模板加载器存储在django.template.loader.template_source_loaders.

当您使用缓存加载器时,那里只会有一个加载器。这样你就可以获取它并调用它的重置函数来重置模板缓存。

这是一些代码片段,我自己没有测试过。

from django.template.loader import template_source_loaders
loader = template_source_loaders[0]
loader.reset()
Run Code Online (Sandbox Code Playgroud)

如果你检查一下django.template.loaders.cached,你会发现 django 只是使用一个变量template_cache来将模板名称保存到模板路径缓存中。它不使用内存缓存。所以django重启时应该重置它。