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

【一】引言

  • 给类视图函数添加装饰器需要借助第三方模块
from django.utils.decorators import method_decorator

【二】三种添加装饰器方式

【1】给类方法加装饰器

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

(1)路由

path('login_view/', views.MyLogin.as_view()),

(2)视图

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 请求")

【2】放在类上面

放在类的上面加装饰器

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

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

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 请求")

【3】重写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 请求")
posted @ 2024-04-07 18:28  Chimengmeng  阅读(3)  评论(0编辑  收藏  举报
/* */