Caching for anonymous users in django

How can I cache pages for anonymous users, but providing them to authorized users in Django 1.6? There used to be a CACHE_MIDDLEWARE_ANONYMOUS_ONLY flag, which sounded perfect, but withdrew.

I ask because on every page there is a menu bar that displays the username and username and profile.

What is the right way to do this? It should be a common problem, but I did not find a suitable way to view the Django documentation.

+6
source share
4 answers

this does not require any code in the view:

{% with cache_timeout=user.is_staff|yesno:"0,300" %} {% cache cache_timeout cacheidentifier user.is_staff %} your content here {% endcache %} {% endwith %} 
+2
source

context = {"cache_timeout": 300 if request.user.is_anonymous () else 0}

{% load cache%}
{% cache cache_timeout "my-cache-fragment"%}
I need to write this only once
{% endcache%}

+1
source

I'm not sure if this is the "right" way to achieve this, but I use the template tag {% cache%} to get around this. The dynamic bit of the template username is in my base template, and I cache the rest as shown below:

 {% extends "base.html" %} {% load cache %} {% block content %} {% cache 86400 key-name %} <h1>My Template in here</h1> {% endcache %} {% endblock content %} 

By specifying a key-name, you can use the following in the view to clear the cache if you need to update it manually:

 key = django.core.cache.utils.make_template_fragment_key('key-name') cache.delete(key) 
0
source

You can use the following approach by creating a decorator:

 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) else: return cache_page(timeout)(view_func)(request, *args, **kwargs) return _wrapped_view return decorator 

then in your urls:

 url(r'^$', cache_for_anonim(3600)(MyView.as_view())), 

source: http://codeinpython.blogspot.com/2017/01/caching-for-anonymous-non-authenticated.html

-1
source

All Articles