How to remove a fragment of a cached template in Django?

I used to set up a cached HTML snippet in my Django template as follows.

{% load cache %} {% cache 10000 courseTable %} <!-- Cached HTML --> {% endcache %} 

Now I have updated this cached content and I want to update it. I tried to change the time to no avail:

 {% load cache %} {% cache 0 courseTable %} <!-- Updated Cached HTML --> {% endcache %} 

In this case, the page still displays the old cached HTML.

I also tried removing template tags related to caching and reinserting them. However, in this case, the content simply reverts to the original cached content after re-entering the cache template tags.

What can I do? I do not want to wait about 2 hours to reload my cache.

+4
source share
3 answers

If you can let memcached completely clear, run flush_all cmd or just

 from django.core.cache import cache cache.clear() 

Or you must manually generate the cache key . timeout will not be updated until the key expires.

+7
source

For Django 1.6+ and Django Documentation, you can simply generate a partial search key and delete it:

 from django.core.cache import cache from django.core.cache.utils import make_template_fragment_key cache key for {% cache 500 sidebar username %} key = make_template_fragment_key('sidebar', [username]) cache.delete(key) # invalidates cached template fragment 

You just need to call make_template_fragment_key with your previously defined courseTable argument.

+4
source

Prior to Django 1.6, the cache template tag built its cache keys more or less in the body of the tag definition (see here ). Starting from 1.6, the fragment fragment cache keys were built using the django.core.cache.utils.make_template_fragment_key function (see here ).

In any case, you can delete a specific cached fragment using or defining make_template_fragment_key to get its cache key like this:

 from __future__ import unicode_literals import hashlib from django.core.cache import cache from django.utils.encoding import force_bytes from django.utils.http import urlquote TEMPLATE_FRAGMENT_KEY_TEMPLATE = 'template.cache.%s.%s' def make_template_fragment_key(fragment_name, vary_on=None): if vary_on is None: vary_on = () key = ':'.join(urlquote(var) for var in vary_on) args = hashlib.md5(force_bytes(key)) return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, args.hexdigest()) def delete_cached_fragment(fragment_name, *args): cache.delete(make_template_fragment_key(fragment_name, args or None)) delete_cached_fragment('my_fragment', 'other', 'vary', 'args') 

This code is directly copied from the django code base, so this license and copyright apply.

+2
source

Source: https://habr.com/ru/post/1414665/


All Articles