Python中的Swagger数组响应不适用于生成的客户端

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

我正在使用带有Flask和connexion的Swagger在Python中实现REST API。我在Python中使用swagger-codegen生成了一个客户端。当使用带有返回数组的GET调用的接口时,我可以在调试日志记录中看到响应已按预期到达客户端,但客户端未正确处理它。

这是我招摇的Yaml定义

schemes:
 - http
paths:             
  /elements: 
      get:
        summary: 'Fetch elements from the database'
        operationId: elements.get_elements
        responses:
          '200':
              description: Fetch elements from the database
              schema:
                 type: array
                 items:
                 $ref: '#/definitions/element'   


definitions:
  element:
    type: object
    properties:
      id:           { type: string }
      desc:         { type: string }

这是我的API的实现

from flask import jsonify

elements = [{'id':'1', 'desc':'description1'},{'id':'2', 'desc':'description2'}]


def get_elements():
    """
        Gets elements
    """
    return jsonify(elements)

这是我的客户通话记录

>>> api_instance.elements_get_elements()
2019-11-26 11:28:02,946 DEBUG Starting new HTTP connection (1): localhost:5123
2019-11-26 11:28:02,946 DEBUG Starting new HTTP connection (1): localhost:5123
send: b'GET /elements HTTP/1.1\r\nHost: localhost:5123\r\nAccept-Encoding: identity\r\nUser-Agent: Swagger-Codegen/1.0.0/python\r\nContent-Type: application/json\r\n\r\n'
reply: 'HTTP/1.0 200 OK\r\n'
header: Content-Type: application/json
header: Content-Length: 108
header: Server: Werkzeug/0.16.0 Python/3.6.8
header: Date: Tue, 26 Nov 2019 10:28:02 GMT
2019-11-26 11:28:02,953 DEBUG http://localhost:5123 "GET /elements HTTP/1.1" 200 108
2019-11-26 11:28:02,953 DEBUG http://localhost:5123 "GET /elements HTTP/1.1" 200 108
2019-11-26 11:28:02,954 DEBUG response body: [
  {
    "desc": "description1", 
    "id": "1"
  }, 
  {
    "desc": "description2", 
    "id": "2"
  }
]

2019-11-26 11:28:02,954 DEBUG response body: [
  {
    "desc": "description1", 
    "id": "1"
  }, 
  {
    "desc": "description2", 
    "id": "2"
  }
]

{'desc': None, 'id': None}

您可以看到最后一行显示的结果不是我对响应数组的预期解释

python swagger swagger-codegen
1个回答
0
投票

Flask按顺序对JSON密钥进行排序,但是可以通过配置JSON_SORT_KEYS选项来覆盖它。

例如

app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False

请参阅official documentation了解更多详细信息。

这会改变您的输出:

 [
  {
    "id": "1",
    "desc": "description1"

  }, 
  {
     "id": "2",
     "desc": "description2"
  }
]

我认为这是您的期望?

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