Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access template cache? - Django

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

like image 878
RadiantHex Avatar asked Nov 22 '10 11:11

RadiantHex


People also ask

Where is Django cache stored?

If you're building your own backend, you can use the standard cache backends as reference implementations. You'll find the code in the django/core/cache/backends/ directory of the Django source.

How do I know if Django cache is working?

If cache. get() returns the set value it means that cache is working as it should. Otherwise it will return None . An other option is to start memcached with $ memcached -vv , since it will log all the cache accesses to the terminal.

How does Django store cache data?

If you would like to store cached data in the database, Django has a backend for this purpose. To save cached data in the database, you just need to create a table in the database by going to the settings.py file, setting BACKEND to django. core. cache.

Where should templates go in Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.


1 Answers

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())
like image 166
kafuchau Avatar answered Oct 14 '22 22:10

kafuchau