Caching for anonymous users in django

2019-06-17 16:19发布

问题:

How would I go about caching pages for anonymous users but rendering them for authorized users in Django 1.6? There used to be a CACHE_MIDDLEWARE_ANONYMOUS_ONLY flag that sounded perfect, but that has gotten removed.

I'm asking because every page has a menu bar that displays the logged in user's name and a link to his/her profile.

What's the correct way of doing this? Must be a common problem, but I haven't found the right way from looking through the Django documentation.

回答1:

this does not require any code in a view:

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


回答2:

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

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



回答3:

I'm not sure if this is the 'correct' way of achieving this but I am using the {% cache %} template tag to get around this problem. The dynamic username bit of the template is in my base template and I cache the rest as 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 then use the below in a view to clear out the cache if you need to refresh manually:

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


回答4:

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