如何在 Django 1.9 中重置模板加载器缓存?

问题描述 投票:0回答:3

我曾经能够在所有加载器上导入

django.template.loader.template_source_loaders
并调用
reset()
来重置所有模板加载器缓存,但这不再起作用。

如何在 Django 1.9 中重置模板加载器缓存?

我的设置,以防万一这有用:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'accounts/templates')],
        'APP_DIRS': True
    }
]

这就是我加载模板的方式:

from django.template import TemplateDoesNotExist
from django.template.loader import get_template
from django.template.response import TemplateResponse
from django.http import HttpResponse
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import ensure_csrf_cookie

@never_cache
@ensure_csrf_cookie
def view(request, **kwargs):
    try:
        template = get_template('index.html')
    except TemplateDoesNotExist:
        return HttpResponse("Run `make template`")

    return TemplateResponse(request, template)

我在使用内置

runserver
且 DEBUG=True 的本地开发中遇到此问题。该问题不适用于生产,因为模板将始终存在。

django django-templates
3个回答
2
投票

请注意,这个问题和答案已经有好几年了。在编写本文时,Django 默认情况下不缓存其模板。从那时起发生了一些变化,例如

  • Django 3.2 起,使用缓存模板加载器缓存的模板将在开发过程中正确重新加载。
  • Django 1.11 开始,当
    debug
    False
    时,Django 开始缓存模板。
  • Django 4.1 开始,Django 开始缓存模板,无论
    debug
    的值如何。

这是我 2016 年 5 月的原始答案:

Django 不缓存其模板,但它缓存应用程序目录加载器使用的应用程序模板目录列表。如果您创建一个新目录,例如

polls/templates
启动服务器后,Django 将不会拾取此目录中的模板,直到服务器重新启动为止。


0
投票

真的很简单:

from django.template.utils import get_app_template_dirs
get_app_template_dirs.cache_clear()

0
投票
from django.template.loader import engines

for engine in engines.all():
    engine.engine.template_loaders[0].reset()

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

© www.soinside.com 2019 - 2024. All rights reserved.