当前位置:   article > 正文

109、Flask-RESTful_flask_restful命令行启动

flask_restful命令行启动

一、Flask-RESTful起步

Flask-RESTful是用于快速构建REST API的Flask扩展。

1 安装

pip install flask-restful

2 Hello World

  1. from flask import Flask
  2. from flask_restful import Resource, Api
  3. app = Flask(__name__)
  4. api = Api(app)
  5. class HelloWorldResource(Resource):
  6. def get(self):
  7. return {'hello': 'world'}
  8. def post(self):
  9. return {'msg': 'post hello world'}
  10. api.add_resource(HelloWorldResource, '/')
  11. # 此处启动对于1.0之后的Flask可有可无
  12. if __name__ == '__main__':
  13. app.run(debug=True)

二、Flask-RESTful视图

1 为路由起名

通过endpoint参数为路由起名

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'}

三、Flask-RESTful请求处理

Flask-RESTful 提供了RequestParser类,用来帮助我们检验和转换请求数据。

  1. from flask_restful import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('rate', type=int, help='Rate cannot be converted', location='args')
  4. parser.add_argument('name')
  5. args = parser.parse_args()

使用步骤:

  1. 创建RequestParser对象
  2. 向RequestParser对象中添加需要检验或转换的参数声明
  3. 使用parse_args()方法启动检验处理
  4. 检验之后从检验结果中获取参数时可按照字典操作或对象属性操作

args.rate 或 args['rate']

参数说明

1 required

描述请求是否一定要携带对应参数,默认值为False

  • True 强制要求携带

若未携带,则校验失败,向客户端返回错误信息,状态码400

  • False 不强制要求携带

若不强制携带,在客户端请求未携带参数时,取出值为None

  1. class DemoResource(Resource):
  2. def get(self):
  3. rp = RequestParser()
  4. rp.add_argument('a', required=False)
  5. args = rp.parse_args()
  6. return {'msg': 'data={}'.format(args.a)}

2 help

参数检验错误时返回的错误描述信息

rp.add_argument('a', required=True, help='missing a param')

3 action

描述对于请求参数中出现多个同名参数时的处理方式

  • action='store' 保留出现的第一个, 默认
  • action='append' 以列表追加保存所有同名参数的值

rp.add_argument('a', required=True, help='missing a param', action='append')

4 type

描述参数应该匹配的类型,可以使用python的标准数据类型string、int,也可使用Flask-RESTful提供的检验方法,还可以自己定义

  • 标准类型

rp.add_argument('a', type=int, required=True, help='missing a param', action='append')

  • Flask-RESTful提供

检验类型方法在flask_restful.inputs模块中

    • url
    • regex(指定正则表达式)

from flask_restful import inputs rp.add_argument('a', type=inputs.regex(r'^\d{2}&'))

    • natural 自然数0、1、2、3...
    • positive 正整数 1、2、3...
    • int_range(low ,high) 整数范围

rp.add_argument('a', type=inputs.int_range(1, 10))

    • boolean
  1. def mobile(mobile_str):
  2. """
  3. 检验手机号格式
  4. :param mobile_str: str 被检验字符串
  5. :return: mobile_str
  6. """
  7. if re.match(r'^1[3-9]\d{9}$', mobile_str):
  8. return mobile_str
  9. else:
  10. raise ValueError('{} is not a valid mobile'.format(mobile_str))
  11. rp.add_argument('a', type=mobile)

5 location

描述参数应该在请求数据中出现的位置

  1. # Look only in the POST body
  2. parser.add_argument('name', type=int, location='form')
  3. # Look only in the querystring
  4. parser.add_argument('PageSize', type=int, location='args')
  5. # From the request headers
  6. parser.add_argument('User-Agent', location='headers')
  7. # From http cookies
  8. parser.add_argument('session_id', location='cookies')
  9. # From json
  10. parser.add_argument('user_id', location='json')
  11. # From file uploads
  12. parser.add_argument('picture', location='files')

也可指明多个位置

parser.add_argument('text', location=['headers', 'json'])

四、Flask-RESTful响应处理

1 序列化数据

Flask-RESTful 提供了marshal工具,用来帮助我们将数据序列化为特定格式的字典数据,以便作为视图的返回值。

  1. from flask_restful import Resource, fields, marshal_with
  2. resource_fields = {
  3. 'name': fields.String,
  4. 'address': fields.String,
  5. 'user_id': fields.Integer
  6. }
  7. class Todo(Resource):
  8. @marshal_with(resource_fields, envelope='resource')
  9. def get(self, **kwargs):
  10. return db_get_todo()

也可以不使用装饰器的方式

  1. class Todo(Resource):
  2. def get(self, **kwargs):
  3. data = db_get_todo()
  4. return marshal(data, resource_fields)

示例

  1. # 用来模拟要返回的数据对象的类
  2. class User(object):
  3. def __init__(self, user_id, name, age):
  4. self.user_id = user_id
  5. self.name = name
  6. self.age = age
  7. resoure_fields = {
  8. 'user_id': fields.Integer,
  9. 'name': fields.String
  10. }
  11. class Demo1Resource(Resource):
  12. @marshal_with(resoure_fields, envelope='data1')
  13. def get(self):
  14. user = User(1, 'itcast', 12)
  15. return user
  16. class Demo2Resource(Resource):
  17. def get(self):
  18. user = User(1, 'itcast', 12)
  19. return marshal(user, resoure_fields, envelope='data2')

2 定制返回的JSON格式

需求

想要接口返回的JSON数据具有如下统一的格式

{"message": "描述信息", "data": {要返回的具体数据}}

在接口处理正常的情况下, message返回ok即可,但是若想每个接口正确返回时省略message字段

  1. class DemoResource(Resource):
  2. def get(self):
  3. return {'user_id':1, 'name': 'itcast'}

对于诸如此类的接口,能否在某处统一格式化成上述需求格式?

{"message": "OK", "data": {'user_id':1, 'name': 'itcast'}}

解决

Flask-RESTful的Api对象提供了一个representation的装饰器,允许定制返回数据的呈现格式

  1. api = Api(app)
  2. @api.representation('application/json')
  3. def handle_json(data, code, headers):
  4. # TODO 此处添加自定义处理
  5. return resp

Flask-RESTful原始对于json的格式处理方式如下:

代码出处:flask_restful.representations.json

  1. from flask import make_response, current_app
  2. from flask_restful.utils import PY3
  3. from json import dumps
  4. def output_json(data, code, headers=None):
  5. """Makes a Flask response with a JSON encoded body"""
  6. settings = current_app.config.get('RESTFUL_JSON', {})
  7. # If we're in debug mode, and the indent is not set, we set it to a
  8. # reasonable value here. Note that this won't override any existing value
  9. # that was set. We also set the "sort_keys" value.
  10. if current_app.debug:
  11. settings.setdefault('indent', 4)
  12. settings.setdefault('sort_keys', not PY3)
  13. # always end the json dumps with a new line
  14. # see https://github.com/mitsuhiko/flask/pull/1262
  15. dumped = dumps(data, **settings) + "\n"
  16. resp = make_response(dumped, code)
  17. resp.headers.extend(headers or {})
  18. return resp

为满足需求,做如下改动即可

  1. @api.representation('application/json')
  2. def output_json(data, code, headers=None):
  3. """Makes a Flask response with a JSON encoded body"""
  4. # 此处为自己添加***************
  5. if 'message' not in data:
  6. data = {
  7. 'message': 'OK',
  8. 'data': data
  9. }
  10. # **************************
  11. settings = current_app.config.get('RESTFUL_JSON', {})
  12. # If we're in debug mode, and the indent is not set, we set it to a
  13. # reasonable value here. Note that this won't override any existing value
  14. # that was set. We also set the "sort_keys" value.
  15. if current_app.debug:
  16. settings.setdefault('indent', 4)
  17. settings.setdefault('sort_keys', not PY3)
  18. # always end the json dumps with a new line
  19. # see https://github.com/mitsuhiko/flask/pull/1262
  20. dumped = dumps(data, **settings) + "\n"
  21. resp = make_response(dumped, code)
  22. resp.headers.extend(headers or {})
  23. return resp

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/72960
推荐阅读
相关标签
  

闽ICP备14008679号