关于视图

1 为路由起名

通过endpoint参数为路由起名

  1. api.add_resource(HelloWorldResource, '/', endpoint='HelloWorld')

2 蓝图中使用

  1. from flask import Flask, Blueprint
  2. from flask_restful import Api, Resource
  3. app = Flask(__name__)
  4. user_bp = Blueprint('user', __name__)
  5. user_api = Api(user_bp)
  6. class UserProfileResource(Resource):
  7. def get(self):
  8. return {'msg': 'get user profile'}
  9. user_api.add_resource(UserProfileResource, '/users/profile')
  10. app.register_blueprint(user_bp)

3 装饰器

使用method_decorators添加装饰器

  • 为类视图中的所有方法添加装饰器

    1. def decorator1(func):
    2. def wrapper(*args, **kwargs):
    3. print('decorator1')
    4. return func(*args, **kwargs)
    5. return wrapper
    6. def decorator2(func):
    7. def wrapper(*args, **kwargs):
    8. print('decorator2')
    9. return func(*args, **kwargs)
    10. return wrapper
    11. class DemoResource(Resource):
    12. method_decorators = [decorator1, decorator2]
    13. def get(self):
    14. return {'msg': 'get view'}
    15. def post(self):
    16. return {'msg': 'post view'}
  • 为类视图中不同的方法添加不同的装饰器

    1. class DemoResource(Resource):
    2. method_decorators = {
    3. 'get': [decorator1, decorator2],
    4. 'post': [decorator1]
    5. }
    6. # 使用了decorator1 decorator2两个装饰器
    7. def get(self):
    8. return {'msg': 'get view'}
    9. # 使用了decorator1 装饰器
    10. def post(self):
    11. return {'msg': 'post view'}
    12. # 未使用装饰器
    13. def put(self):
    14. return {'msg': 'put view'}