Resetting cache for Django cached template loader

后端 未结 4 1256
花落未央
花落未央 2021-01-02 09:23

Django 1.2 introduced a new template loader, that stores data in cache ( django.template.loaders.cached.Loader ).

Unfortunatly, i failed to find any inf

4条回答
  •  北海茫月
    2021-01-02 09:59

    Only this solution will work guaranteed, including production environment, without server restart and even if you're using 'django.template.loaders.cached.Loader' backend:

    import django.template.loader
    
    def reset_template_cache():
        if django.template.loader.template_source_loaders:
            for t in django.template.loader.template_source_loaders:
                t.reset()
    

    This is explicit absolute import, which can be used for patching global variables. You can be sure that other answers are wrong after using {% include 'some_template' %} template tag (cache of the 'some_template' not be reseted after using loader.reset() where loader is just iterator of template_source_loaders imported by relative import.

    I used this method for invalidation the templates storing in the database (created by django-dbtemplates library), and which included into normal templates by {% include %} template tag.

提交回复
热议问题