Global variable/Variable caching in Django


In my website, I want to present to the user the most viewed product categories in a sidebar, in multiple pages.

so in each different view I have:

variables = RequestContext(request, {
   'most_viewed_cats': calculate_most_viewed_categories()

and in the various templates

{% include "list_most_viewed_categories" %}

and in that one:

{% for cat in most_viewed_cats %}
    {{ }}
{% empty %}
    </ul>No categories to show.<ul>
{% endfor %} 

However, I would like to calculate the most_viewed_categories value only once every 2 days or so, instead of calculating it in every view.

I know views can be cached, but this is more of a variable caching. Is it possible to cache this variable somewhere in the Django server and renew it only after that period of time? How would one go about doing this?

Thank you

Asked By: user1034697



If it’s something you’d like to reuse across the whole site, you would probably do best to create a context processor that’s going to always populate the template context with the variable containing the most viewed categories

from django.core.cache import get_cache

CACHE_KEY_MOST_VIEWED_CATEGORIES = 'most_viewed_categories'
cache = get_cache('default')

def _get_most_viewed_categories():
    raise NotImplemented("Haven't figured out how to collect the value and cache it")

def most_viewed_categories(request):
    '''Provides the most viewed categories for every template context.'''

    return {
        'most_viewed_categories': cache.get(CACHE_KEY_MOST_VIEWED_CATEGORIES, 

But in any case, for caching a value in the database, you’ll need to obtain the cache and use cache.set and cache.get to store and retrieve the value.

Answered By: Filip Dupanović