-->

How to cache a view only for unauthenticated users

2019-08-20 07:28发布

问题:

I have a view which I want to cache only for unauthenticated users. The view should be something like this:

@cache_page_for_guests(60 * 15)
def my_view(request):

I've looked at the docs but could not but could not find any hints about this.

Actually my question is exactly as this, which is unanswered, and I could not make sense of the comments.

So appreciate your help.

回答1:

Write a custom decorator like this:

from django.views.decorators.cache import cache_page

def cache_page_for_guests(cache_life_span):
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            return cache_page(cache_life_span, key_prefix="_auth_%s_" % not request.user.is_authenticated())(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return decorator

Then in view

@cache_page_for_guests(60 * 15)
def my_view(request):


回答2:

from functools import wraps
from django.views.decorators.cache import cache_page


def cache_page_for_guests(*cache_args, **cache_kwargs):
    def inner_decorator(func):
        @wraps(func)
        def inner_function(request, *args, **kwargs):
            if not request.user.is_authenticated:
                return cache_page(*cache_args, **cache_kwargs)(func)(request, *args, **kwargs)
           return func(request, *args, **kwargs)
        return inner_function
    return inner_decorator

you can use cache_page_for_guest just like cache_page. It'll accept the same arguments as of cache_page. Based on the user's authentication, it'll show either a normal view or a cached view.

@cache_page_for_guests(60 * 15)
def my_view(request):