Python Swagger响应变为null(Flask,Flask_Restplus)

问题描述 投票:0回答:1

我能够在终端中查看响应内容,但在swagger UI中,它显示为空。

问题:要调试我试图在函数ret中打印变量json_response_from_dict(dict_)中的值,它显示我通过swagger UI输入的值。但是在Swagger UI的回应中,它变得空洞。

Empty response body in swagger

但是在终端的响应中,它显示<Response 141 bytes [200 OK]>和ret in terminal的值也显示{"rec_id": 464, "frame_id_prob": [[1, 0.1], [2, 0.1], [3, 0.1], [4, 0.1], [5, 0.6]], "comment": "these frames suit everyone", "mine_id": NaN}我无法弄清楚值丢失的位置。

MCVE:

from flask import Flask, Blueprint, request, Response
from flask_restplus import Resource, Api, fields
from flask.views import MethodView
import json
import numpy as np
def json_response_from_dict(dict_):
    """converts a python dictionary to a json string, and returns
    a HHTP response for a JSON string
    dict_ -- input python dictionary
    """

    ret = json.dumps(dict_)
    print(ret)
    resp = Response(response=ret,
                    status=200,
                    mimetype="application/json")
    print(resp)
    return resp


app = Flask(__name__)



api_v1 = Blueprint('api', __name__, url_prefix='/api/1')

api = Api(api_v1, version='1.0', title='my API',
    description='my API',
)
ns = api.namespace('my', description='my operations')

myModel = api.model('my Model', {
    'rec_id': fields.Integer(readOnly=True, description='Random Choice'),
    'comment': fields.String(required=True, description='Comments'),
    'mine_id' : fields.String(required=True, description='unique ECP ID')
})


# Register blueprint at URL
# (URL must match the one given to factory function above)
app.register_blueprint(api_v1)


@ns.route("/dev/get_rec_id", methods=["POST"])
@ns.param('mine_id', 'unique ECP ID')
class RecommendationService(Resource):
    @ns.doc('path to generate a unique recommendationid, and to determine which predictions can be made for. Expected/optional input :      JSON string as a https html data objects with keys: mine_id -- unique ECP ID. If this is not provided generic recommendations will be provided.')
    @ns.marshal_list_with(myModel)
    def post(self):
        mine_id = np.nan
        if request.is_json:
            mine_id = request.json.get('mine_id', np.nan)

        return json_response_from_dict({
            'rec_id': np.random.choice(1000),
            'fun_id_prob': [[1, 0.1], [2, 0.1], [3, 0.1], [4, 0.1], [5, 0.6]],
            'comment': 'these games suit everyone',
            'mine_id': mine_id
             })




if __name__ == '__main__':
    app.run(debug=True)

我按照here的建议将功能更改为

@ns.route("/dev/get_rec_id", methods=["POST"])
@ns.param('mine_id', 'unique ECP ID')
class RecommendationService(Resource):
    @ns.doc('path to generate a unique recommendationid, and to determine which frames predictions can be made for. Expected/optional input :       JSON string as a https html data objects with keys: mine_id -- unique ECP ID. If this is not provided generic frames recommendations will be provided.')
    @ns.marshal_list_with(myModel)
    def post(self):
        mine_id = np.nan
        if request.is_json:
            mine_id = request.json.get('mine_id', np.nan)

        return {'rec_id': np.random.choice(1000),
            'fun_id_prob': [[1, 0.1], [2, 0.1], [3, 0.1], [4, 0.1], [5, 0.6]],
            'comment': 'these games suit everyone',
            'mine_id': mine_id
             }

但同样的问题仍然存在。

python flask swagger flask-restplus
1个回答
0
投票
@ns.route("/dev/get_rec_id", methods=["POST"])
@ns.param('mine_id', 'unique ECP ID')
class RecommendationService(Resource):
    @ns.doc('path to generate a unique recommendationid, and to determine which frames predictions can be made for. Expected/optional input :       JSON string as a https html data objects with keys: mine_id -- unique ECP ID. If this is not provided generic frames recommendations will be provided.')
    @ns.marshal_list_with(myModel)
    def post(self):
        mine_id = np.nan
        if request.is_json:
            mine_id = request.json.get('mine_id', np.nan)

        return {'rec_id': np.random.choice(1000),
            'fun_id_prob': [[1, 0.1], [2, 0.1], [3, 0.1], [4, 0.1], [5, 0.6]],
            'comment': 'these games suit everyone',
            'mine_id': mine_id
             }

在这个签名不匹配,即fun_id_prob不在API签名,也因为某些原因在调用X-Fields时,它需要保持为空。

只是用

@ns.route("/dev/get_rec_id", methods=["POST"])
@ns.param('mine_id', 'unique ECP ID')
class RecommendationService(Resource):
    @ns.doc('path to generate a unique recommendationid, and to determine which frames predictions can be made for. Expected/optional input :       JSON string as a https html data objects with keys: mine_id -- unique ECP ID. If this is not provided generic frames recommendations will be provided.')
    @ns.marshal_list_with(myModel)
    def post(self):
        mine_id = np.nan
        if request.is_json:
            mine_id = request.json.get('mine_id', np.nan)

        return {'rec_id': np.random.choice(1000),
            'comment': 'these games suit everyone',
            'mine_id': mine_id
             }

或者添加列表到签名,它将工作:)。

© www.soinside.com 2019 - 2024. All rights reserved.