问题
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