Advantage classes view
类视图的好处是支持继承,但是类视图不能跟函数视图一样,
写完类视图还需要通过app.add_url_rule(url_rule,view_func)来进行注册
from flask import Flask,render_template,views
app = Flask(__name__,)
Decorator
- Class view decorator, decorators need to rebuild the class attribute class view, he is a list, which is filled with all the decorators
- If you are using a function of view, the definition of decorators must be placed app.route below, otherwise not have any effect
def test1(func):
def inner(*args,**kwargs):
print('before1')
result = func(*args,**kwargs)
print('after1')
return result
return inner
def test2(func):
def inner(*args,**kwargs):
print('before2')
result = func(*args,**kwargs)
print('after2')
return result
return inner
Class View
class UserView(views.MethodView):
methods = ['GET',"POST"]
decorators = [test1,test2] # 装饰器列表
def get(self):
print('get')
return 'get'
def post(self):
print('post')
return 'post'
app.add_url_rule('/user', view_func=UserView.as_view('user')) # endpoint
if __name__ == '__main__':
app.run()