如何仅为未经身份验证的用户缓存视图? [英] How to cache a view only for unauthenticated users?

查看:92
本文介绍了如何仅为未经身份验证的用户缓存视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,只想为未经身份验证的用户缓存. 视图应该是这样的:

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.

非常感谢您的帮助.

推荐答案

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

您可以像cache_page一样使用cache_page_for_guest.它将接受与cache_page相同的参数.根据用户的身份验证,它将显示普通视图或缓存视图.

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):

这篇关于如何仅为未经身份验证的用户缓存视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆