视频加载失败

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

344 字
2 分钟
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 请求")

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

打赏
Django框架之CBV添加装饰器的三种方式
https://firefly.cuteleaf.cn/posts/framework/python/django/base/220django框架之cbv添加装饰器的三种方式/
作者
Dream
发布于
2023-07-25
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Dream
Hello, I'm Dream.
公告
欢迎来到我的博客!爱学习爱进步。
分类
标签
最新动态
站点统计
文章
300
分类
5
标签
26
总字数
640,882
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
Vercel
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录