flask restful:如何使用 fields.Dict() 记录响应主体?
flask restful: how to document response body with fields.Dict()?
在 flask-restplus
中,我想对具有嵌套列表结构的响应主体建模,因此无论何时进行 api 调用,响应主体都会返回我所期望的。在响应体中,它有一个嵌套结构,我不知道如何记录它。我要使用 fields.Dict()
吗?谁能告诉我如何在 flask-restplus
中做到这一点?
响应正文:
{
"score": 0,
"category": "low",
"guidance": "string",
"is_ready": true,
"used_features": [
{
"name": "hear_rate",
"value": 1002,
"range_value": [
10,
1000,
10000,
20000
],
"range_frequency": [
80,
15,
2,
1
],
"importance": 1
},
{
"name": "pressure",
"value": 400,
"range_value": [
10,
1000,
3000
],
"range_frequency": [
85,
10,
5
],
"importance": 2
}
]
}
我的部分解决方案:
这是我的部分解决方案
from flask import Flask, jsonify
from flask_restplus import Api, Resource, fields, reqparse, inputs
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
payload = api.model('Payload', {
'score': fields.Integer,
'category': fields.String,
'guidance': fields.String,
'is_ready': fields.Boolean,
## how to add used features arrays
})
@ns.route('/')
class AResource(Resource):
@ns.expect(payload)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('score', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('guidance', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('is_ready', type= bool, required=True)
try: # Will raise an error if date can't be parsed.
args = parser.parse_args() # type "dict"
return jsonify(args)
except:
return None, 400
if __name__ == '__main__':
app.run(debug=True)
在我尝试的代码中,我无法想出如何为 used_features
字典建模的解决方案。有没有办法解决上述尝试的缺陷?谁能指出我如何在可以正确建模响应体的地方进行这项工作?我要在我的代码中使用 Dict
还是 Nested
?还有什么想法吗?谢谢
Use @ns.marshal_with(payload).
The decorator marshal_with() is what actually takes your data object and applies the field filtering. The marshalling can work on single objects, dicts, or lists of objects.
Marshalling Resource Link: https://flaskrestplus.readthedocs.io/en/stable/marshalling.html
并为模型 used_features 使用 fields.Nested。我已经在下面的代码中展示了如何使用它。
from flask import Flask, jsonify
from flask_restplus import Namespace, Resource, fields, reqparse
from flask_restplus import Api
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
used_features = {}
used_features['name'] = fields.String(attribute='name')
used_features['value'] = fields.Integer(attribute='value')
used_features['range_value'] = fields.List(
fields.Integer, attribute='range_value')
used_features['range_frequency'] = fields.List(
fields.Integer, attribute='range_frequency')
used_features['importance'] = fields.Integer(attribute='importance')
used_features_payload = api.model('feature_payload', used_features)
payload = api.model('Payload', {
'score': fields.Integer,
'category': fields.String,
'guidance': fields.String,
'is_ready': fields.Boolean,
'used_features': fields.Nested(used_features_payload)
# how to add used features arrays
})
@ns.route('/')
class AResource(Resource):
@ns.expect(payload)
@ns.marshal_with(payload)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('score', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('guidance', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('is_ready', type=bool, required=True)
try: # Will raise an error if date can't be parsed.
args = parser.parse_args() # type "dict"
return jsonify(args)
except:
return None, 400
if __name__ == '__main__':
app.run(debug=True, port=1234)
https://flask-restplus.readthedocs.io/en/stable/marshalling.html
from flask_restplus import fields, Namespace, marshal
api = Namespace("Student data")
db_data = Student_details.query.all()
data_marshal_obj = api.model(" Data", {
"id": fields.String(),
"number": fields.Integer(),
"house_name": fields.String(),
})
return {'id': str(student.id),"page_data": marshal(db_data, data_marshal_obj)}
flask restpluse 中的自定义响应编组
在 flask-restplus
中,我想对具有嵌套列表结构的响应主体建模,因此无论何时进行 api 调用,响应主体都会返回我所期望的。在响应体中,它有一个嵌套结构,我不知道如何记录它。我要使用 fields.Dict()
吗?谁能告诉我如何在 flask-restplus
中做到这一点?
响应正文:
{
"score": 0,
"category": "low",
"guidance": "string",
"is_ready": true,
"used_features": [
{
"name": "hear_rate",
"value": 1002,
"range_value": [
10,
1000,
10000,
20000
],
"range_frequency": [
80,
15,
2,
1
],
"importance": 1
},
{
"name": "pressure",
"value": 400,
"range_value": [
10,
1000,
3000
],
"range_frequency": [
85,
10,
5
],
"importance": 2
}
]
}
我的部分解决方案:
这是我的部分解决方案
from flask import Flask, jsonify
from flask_restplus import Api, Resource, fields, reqparse, inputs
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
payload = api.model('Payload', {
'score': fields.Integer,
'category': fields.String,
'guidance': fields.String,
'is_ready': fields.Boolean,
## how to add used features arrays
})
@ns.route('/')
class AResource(Resource):
@ns.expect(payload)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('score', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('guidance', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('is_ready', type= bool, required=True)
try: # Will raise an error if date can't be parsed.
args = parser.parse_args() # type "dict"
return jsonify(args)
except:
return None, 400
if __name__ == '__main__':
app.run(debug=True)
在我尝试的代码中,我无法想出如何为 used_features
字典建模的解决方案。有没有办法解决上述尝试的缺陷?谁能指出我如何在可以正确建模响应体的地方进行这项工作?我要在我的代码中使用 Dict
还是 Nested
?还有什么想法吗?谢谢
Use @ns.marshal_with(payload).
The decorator marshal_with() is what actually takes your data object and applies the field filtering. The marshalling can work on single objects, dicts, or lists of objects. Marshalling Resource Link: https://flaskrestplus.readthedocs.io/en/stable/marshalling.html
并为模型 used_features 使用 fields.Nested。我已经在下面的代码中展示了如何使用它。
from flask import Flask, jsonify
from flask_restplus import Namespace, Resource, fields, reqparse
from flask_restplus import Api
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
used_features = {}
used_features['name'] = fields.String(attribute='name')
used_features['value'] = fields.Integer(attribute='value')
used_features['range_value'] = fields.List(
fields.Integer, attribute='range_value')
used_features['range_frequency'] = fields.List(
fields.Integer, attribute='range_frequency')
used_features['importance'] = fields.Integer(attribute='importance')
used_features_payload = api.model('feature_payload', used_features)
payload = api.model('Payload', {
'score': fields.Integer,
'category': fields.String,
'guidance': fields.String,
'is_ready': fields.Boolean,
'used_features': fields.Nested(used_features_payload)
# how to add used features arrays
})
@ns.route('/')
class AResource(Resource):
@ns.expect(payload)
@ns.marshal_with(payload)
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('score', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('guidance', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('is_ready', type=bool, required=True)
try: # Will raise an error if date can't be parsed.
args = parser.parse_args() # type "dict"
return jsonify(args)
except:
return None, 400
if __name__ == '__main__':
app.run(debug=True, port=1234)
https://flask-restplus.readthedocs.io/en/stable/marshalling.html
from flask_restplus import fields, Namespace, marshal
api = Namespace("Student data")
db_data = Student_details.query.all()
data_marshal_obj = api.model(" Data", {
"id": fields.String(),
"number": fields.Integer(),
"house_name": fields.String(),
})
return {'id': str(student.id),"page_data": marshal(db_data, data_marshal_obj)}