Resetting cache for Django cached template loader

。_饼干妹妹 提交于 2019-12-04 19:30:24

问题


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

Unfortunatly, i failed to find any info on how the cache is invalidated and when and how it is reset.

I want to use this on my server, but i'm not sure, that it would reset on django restart (that would be enough for me).


回答1:


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.




回答2:


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 :)




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/4071221/resetting-cache-for-django-cached-template-loader

工具导航Map