Grab html from memcached if found, if not render and save to memcached

265 Views Asked by At

For a specific controller's action, how would I first check to see HTML is in memcached, and yes then render from cache.

If not found, render the view page's html, then take that html and store it in memcached for future requests.

I actually want to do it in the controller's action, because I want to see what role the user belongs to, if they are logged in, and other logic

2

There are 2 best solutions below

1
On

The easiest way is to use the cache_page decorator from django.views.decorators.cache.

from django.views.decorators.cache import cache_page

@cache_page(3600)  #1 hour cache time in seconds
def a_view_to_cache(request):
    ...

You can do it explicitly in you template if you want to cache only a part of your rendered html

{% load cache %}
{% cache 3600 cache_block_name %}
    .. my block ..
{% endcache %}
0
On