How do I access template cache? - Django

2019-03-19 13:41发布

I am caching html within a few templates e.g.:

{% cache 900 stats %}
    {{ stats }}
{% endcache %}

Can I access the cache using the low level library? e.g.

html = cache.get('stats')

I really need to have some fine-grained control over the template caching :)


Any ideas? Thanks everyone! :D

2条回答
戒情不戒烟
2楼-- · 2019-03-19 14:32

Looking at the code for the cache templatetag, the key is generated like this:

args = md5_constructor(u':'.join([urlquote(resolve_variable(var, context)) for var in self.vary_on]))
cache_key = 'template.cache.%s.%s' % (self.fragment_name, args.hexdigest())

so you could build something simliar in your view to get the cache directly: in your case, you're not using any vary_on parameters so you could use an empty argument to md5_constructor.

查看更多
ら.Afraid
3楼-- · 2019-03-19 14:38

This is how I access the template cache in my project:

from django.utils.hashcompat import md5_constructor
from django.utils.http import urlquote

def someView(request):
    variables = [var1, var2, var3] 
    hash = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % ('table', hash.hexdigest())

    if cache.has_key(cache_key):
        #do some stuff...

The way I use the cache tag, I have:

    {% cache TIMEOUT table var1 var2 var3 %}

You probably just need to pass an empty list to variables. So, yourvariables and cache_key will look like:

    variables = []
    hash = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % ('stats', hash.hexdigest())
查看更多
登录 后发表回答