第一种
class Index(views.MethodView):
methods = ['GET', 'POST']
decorators = []
def get(self):
return 'GET'
def post(self):
return 'POST'
app.add_url_rule('/index', view_func=Index.as_view(name='index')) # name='index'相当于设置endpoint
Index.as_view内部也会根据请求方式进行反射执行对应函数即执行dispatch_request
app.add_url_rule是进行装饰器路由映射内部执行的函数,本质上也是由add_url_rule添加的映射关系,decorators是添加的装饰器列表
第二种
class Index(views.View):
methods = ['GET', 'POST']
decorators = []
def dispatch_request(self):
print('dispatch_request')
return 'Index!'
app.add_url_rule('/index', view_func=Index.as_view(name='index'))
第二种继承的是views.View,这样就需要写dispatch_request函数,但也不必去进行分发请求,那么就会像FBV一样。
0