简体   繁体   English

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

[英]Python Swagger response becomes null (Flask, Flask_Restplus)

I am able to view response content in the terminal but in the swagger UI, it is showing up empty. 我能够在终端中查看响应内容,但在swagger UI中,它显示为空。

Issue: To debug I tried to print the value from variable ret in the function json_response_from_dict(dict_) and it is showing me the value that I am entering through swagger UI. 问题:要调试我试图在函数json_response_from_dict(dict_)打印变量ret的值,它显示我通过swagger UI输入的值。 But in the response of Swagger UI, it's coming up empty. 但是在Swagger UI的回应中,它变得空洞。

昂首阔步的空响应体

But in the response while in the terminal, it shows <Response 141 bytes [200 OK]> and the value of ret in terminal also shows {"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} I am unable to figure out where the value gets lost. 但是在终端的响应中,它显示<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: 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)

I followed the advice from here and changed the function to 我按照这里的建议并将功能更改为

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

But the same issue still persists. 但同样的问题仍然存在。

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

In this the signature didn't match ie fun_id_prob was not in the API Signature, also for some reason while calling X-Fields , it needs to be kept empty. 在这个签名不匹配,即fun_id_prob不在API签名中,由于某些原因,在调用X-Fields ,它需要保持为空。

Just use 只是用

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

Or Add list to the signature and it will work :). 或者添加列表到签名,它将工作:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM