开发者

How do I access template cache? - Django

开发者 https://www.devze.com 2023-01-26 13:05 出处:网络
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.

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 c开发者_StackOverflow中文版aching :)


Any ideas? Thanks everyone! :D


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消