37-CBV-装饰器

类视图使用装饰器

# 使用 method_decorator装饰器指明被装饰的方法

# 为类视图添加装饰器,可以使用两种方法:
'''
  1. 全局装饰器 @method_decorator(自定义装饰器, name='dispatch')
  2. 单个装饰器 @method_decorator(自定义装饰器, name='get')
'''
  

# 为类中的方法函数添加装饰器:
'''
     1. 单个装饰器 @method_decorator(自定义装饰器)
'''

使用

# urls.py
    path('decor/', views.DemoView.as_view(), name="decor"),
#views.py
# 自定义装饰器
def my_check(func):
    def inner(request, *args, **kwargs):
        if request.session.get('username'): # 判断有没有登录
            return func(request,*args, **kwargs)
        return redirect("/")
    return inner


# 调用装饰器的三种方法
# @method_decorator(my_check, name='dispatch')# 1. 为全部请求方法添加装饰器
@method_decorator(my_check, name='get') # 2. 为特定的方法添加装饰器
class DemoView(View):
    # @method_decorator(my_check)  # 3. 为特定的方法添加装饰器
    def get(self, request):
        print("get方法")
        return HttpResponse("ok")

    def post(self, request):
        print("post方法")
        return HttpResponse("ok")
posted @ 2023-04-03 09:39  测试圈的彭于晏  阅读(21)  评论(0)    收藏  举报