0

通过 Python-2.7、connexion 和 Pycharm 发送正文参数时遇到问题。

api.yaml

swagger: '2.0'
info:
  title: Products Api Backend
  version: "1.0.0"
consumes:
  - application/json
produces:
  - application/json
paths:
  /products:
    post:
      operationId: app.addProduct
      parameters:
      - name: body
        description: Product payload to add
        in: body
        required: true
        schema:
          $ref: '#/definitions/ProductParameters'
      responses:
        200:
          description: Data received and added correctly
          schema:
            type: string
definitions:
  ProductParameters:
    description: Needed attributes for each post request
    properties:
      name:
        type: string
        description: Product name

应用程序.py

import connexion

api = connexion.api

def addProduct(name):
   return 'Product Added'   # or 'Product Added', 200

app = connexion.App(__name__)
app.add_api('api.yaml', strict_validation=True)

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

跑步

r = requests.post(appUrl, data={'name':'Product title here'})
print r
print r.content

返回

<Response [400]>
{
  "detail": "Extra formData parameter(s) name not in spec", 
  "status": 400, 
  "title": null, 
  "type": "about:blank"
}

YAML 在Swagger Editor中验证,但运行 Send Request 给出

ERROR Method Not Allowed
Headers
undefined
Body

将 addProduct() 的返回更改为

'Product Added', 200  

仍然返回 400,所以问题显然在连接级别。

非常感激

4

1 回答 1

0

解决了。

我忘了把 Python 字典变成一个字符串(用于正文),所以

import json
dataDict = {'name':'Product title here'}
dataStr = json.dumps(dataDict)
r = requests.post(appUrl, data=dataStr)

返回 200

Python 字典用于发送表单数据;正文数据需要作为 JSON 字符串发送。

于 2017-02-14T08:58:46.413 回答