How do I access template cache? - Django

淺唱寂寞╮ 提交于 2019-12-04 10:52:49

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4245081/how-do-i-access-template-cache-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!