Flask的CBV如何使用

1
2
3
4
5
6
7
8
9
10
11
12
13
1.导入
from flask import views

2.新建一个类继承views中的MethodView,并在里面重写方法即可
class Index(views.MethodView):
methods=["GET"] #允许的请求方式
def get(self):
pass

ps:如果继承view.View需要重写dispatch_request()方法,MethodView帮助你写好了dispatch_request

3.在app.add_url_rule中注册路由
app.add_url_rule('/',endpoint='index',view_func=index.as_view(name='index')) #as_view中的name必填

CBV装饰器的使用

1
2
3
4
5
6
7
8
9
10
只需要在类中添加一个decorator属性
class Index(views.MethodView):
decorator=() #装饰器的内存地址

cbv源码装饰器部分:
if cls.decorators:
view.__name__ = name
view.__module__ = cls.__module__
for decorator in cls.decorators:
view = decorator(view)