函数装饰器在类方法中的使用方法

CBV中加装饰器

要在CBV视图中使用我们上面的check_login装饰器,有以下三种方式:

都要先导入这个方法: from django.utils.decorators import method_decorator

1. 加在CBV视图的get或post方法上

2. 加在dispatch方法上

3. 直接加在视图类上,但method_decorator必须传 name 关键字参数(如果get方法和post方法都需要登录校验的话就写两个装饰器。

这是我之前写的登录装饰器。

# 登录权限控制(session版)
def check_login(func):
    @wraps(func)
    def inner(request, *args, **kwargs):

        if request.session.get("user"):
            return func(request, *args, **kwargs)
        else:
            next_url = request.path_info
            print(next_url)
            return redirect("/app01/login/?next_url={}".format(next_url))

    return inner

这是函数版的装饰器,直接在类中使用是不行的。

1,直接在get方法或者post方法中加

class UserInfo(views.View):
    @method_decorator(check_login, name="get")
    def get(self, request):
        return HttpResponse("这是一个UserInfo页面!!!")
从csdn搬家过来的可能没有图片,原地址https://blog.csdn.net/weixin_38091140
原文地址:https://www.cnblogs.com/Apy-0816/p/11100273.html