8

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

RadiantHex
  • 24,907
  • 47
  • 148
  • 244

2 Answers2

6

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())
kafuchau
  • 5,573
  • 7
  • 33
  • 38
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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • thanks for this, I tried `cache.get('template.cache.stat_table.d41d8cd98f00b204e9800998ecf8427e')` but it just returns back as None – RadiantHex Nov 22 '10 at 12:31
  • 1
    I couldn't get this to work unless I supplied [] for vary_on - putting in an empty md5_constructor gave a different base64 part of the key. http://stackoverflow.com/questions/4821297/django-how-to-tell-if-a-template-fragment-is-already-cached/4821681#4821681 – Ryan Jan 27 '11 at 20:50