Monday, January 30, 2017

Caching for anonymous (non-authenticated) users in Django

Hi boys and girls,

Recently I was optimizing performance on some of my django sites and needed to cache all views for anonymous users, but still render for authenticated users. Django documentation is silent on this. I've also checked out stackoverflow, but people there recommend using templates, which I don't like. So below I will give you my version of how to solve that.

1. Add this decorator to your
from django.views.decorators.cache import cache_page
from django.utils.decorators import available_attrs
from functools import wraps

def cache_for_anonim(timeout):
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):

            if request.user.is_authenticated():
                return (view_func)(request, *args, **kwargs)
                return cache_page(timeout)(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return decorator

2. Modify your as follows, for all views that need to be cached:
from django.conf.urls import url
from myapp import views

urlpatterns = [
    url(r'^$', views.cache_for_anonim(60*60)(views.IndexView.as_view())),

So now when you visit a page as anonim, it's being fetched from cache. And when you login, the same page is rendered as usual.

Hope that helps.

No comments:

Post a Comment