【14.0】Django框架之CBV添加装饰器的三种方式

发布时间 2023-07-17 17:35:50作者: Chimengmeng

【一】给类方法加装饰器

指名道姓的装 -- 放在方法上面

  • 路由
path('login_view/', views.MyLogin.as_view()),
  • 需要导入一个模块
from django.utils.decorators import method_decorator
  • 视图
from django.views import View
from django.utils.decorators import method_decorator

'''
CBV中Django不建议你直接给类方法加装饰器
无论该装饰器能否正常工作,都不建议加
'''

class MyLogin(View):
    @method_decorator(login_auth)
    def get(self, request):
        return HttpResponse("get 请求")

    @method_decorator(login_auth)
    def post(self, request):
        return HttpResponse("post 请求")

【二】放在类上面

放在类的上面加装饰器

在参数内指向需要装饰的函数

可以指向多个类方法 -- 针对不同的类方法指定不同的装饰器

from django.views import View
from django.utils.decorators import method_decorator

'''
CBV中Django不建议你直接给类方法加装饰器
无论该装饰器能否正常工作,都不建议加
'''
@method_decorator(login_auth,name='get')
@method_decorator(login_auth,name='post')
class MyLogin(View):

    def get(self, request):
        return HttpResponse("get 请求")


    def post(self, request):
        return HttpResponse("post 请求")

【三】重写dispatch方法

在类中自定义 dispatch 方法

这种方法会给类中所有的方法都加上装饰器

from django.views import View
from django.utils.decorators import method_decorator

'''
CBV中Django不建议你直接给类方法加装饰器
无论该装饰器能否正常工作,都不建议加
'''
class MyLogin(View):
    @method_decorator(login_auth)
    def dispatch(self, request, *args, **kwargs):
        pass

    def get(self, request):
        return HttpResponse("get 请求")


    def post(self, request):
        return HttpResponse("post 请求")