【发布时间】:2021-11-24 05:06:33
【问题描述】:
我正在使用flask-restx 记录和格式化我的 api
我有一个应用程序,包括一个目录,其中包含以下格式的 json 模式:http://json-schema.org/draft-07/schema#
(在我的应用程序中,它们保存为 json 文件,在下面的示例中,我将其作为 dict 硬编码以简化示例)
使用架构,我想实现 3 个目标:
- 文档
- 根据要求进行验证
- 解析请求
使用@api.expect(request_model, validate=True)我设法实现了(1)和(2),但是我没有找到使用现有模式进行解析的方法,我不得不创建一个解析器对象reqparse.RequestParser(),并重写参数。
有没有办法从模型中创建RequestParser? (模型是从现有的 json 模式文件创建的)
这是我的代码:
from flask_restx import Api, inputs
api = Api(app, doc='/my_doc_path')
request_schema = {
'type': 'object',
'properties': {
'param1': {'type': 'string'},
'the_date': {"type": "string", "format": "date-time"},
},
'required': ['param1'],
}
request_model = api.schema_model('my_api_model', request_schema)
@api.route('/my_api/<string:id>')
class MyApi(Resource):
@api.expect(request_model, validate=True)
def post(self, id):
"""
my cool app
"""
parser = reqparse.RequestParser()
parser.add_argument('param1', help='some param 1')
parser.add_argument('the_date', type=inputs.datetime_from_iso8601, help='some date_time')
args = parser.parse_args()
do_something(args['param1'], args['the_date'])
有没有办法像这样:
parser = reqparse.RequestParser(request_model)
args = parser.parse_args()
?
【问题讨论】:
标签: python flask flask-restx