Resetting cache for Django cached template loader

后端 未结 4 1181
花落未央
花落未央 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.

    0 讨论(0)
  • 2021-01-02 10:04
    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()
    

    There you go :)

    0 讨论(0)
  • 2021-01-02 10:12

    By digging into django's source, you could find the template loaders for current server instance are stored at django.template.loader.template_source_loaders.

    When you're using cached loader, there would be only one loader out there. So you can get it and calls its reset function to reset template cache.

    Here are some code snippets, I haven't test it myself.

    from django.template.loader import template_source_loaders
    loader = template_source_loaders[0]
    loader.reset()
    

    If you check django.template.loaders.cached, you can see that django simply use one variable template_cache to hold the template name to template path cache. It doesn't use memcached. So it should be reset when django restart.

    0 讨论(0)
  • 2021-01-02 10:13

    The existing solutions written here broke around Django 1.9, due to the template loader system having been refactored. If you try to use the code that imports template_source_loaders and that import fails, try this:

    from django.template.loader import engines
    
    for engine in engines.all():
        engine.engine.template_loaders[0].reset()
    

    This code assumes that your TEMPLATES setting is using the default 'loaders' option, or using only a single django.template.loaders.cached.Loader.

    0 讨论(0)
提交回复
热议问题