Flask入门笔记-14_在类视图中使用装饰器
-
在类视图中,通过类属性method_decorators来设置类视图的装饰器,如果接收一个列表那类视图内所有的方法都使用列表中的装饰器
-
如果接收一个字典:请求方式为k, 列表为v,列表中放装饰器名称, 注意顺序
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
# 装饰器1
def decorator1(f):
def warpper(*args, **kwargs):
print('decorator1')
return f(*args, **kwargs)
return warpper
# 装饰器2
def decorator2(f):
def warpper(*args, **kwargs):
print('decorator2')
return f(*args, **kwargs)
return warpper
class demo(Resource):
# method_decorators = [decorator1] # 让所有的请求方式都使用decorator1装饰器
method_decorators = { # 指定方法使用指定装饰器
'get':[decorator1, decorator2],
'post':[decorator1]
}
def get(self):
return {'demo':'get'}
def post(self):
return {'demo':'post'}
def put(self):
return {'demo':'put'}
api.add_resource(demo, '/')
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000')