首页 > 解决方案 > 使用 Python 的 POST 请求

问题描述

我正在尝试使用 Python 发布一个简单的 POST 请求,但我收到了意外的错误消息。

文档示例如下:

如果我尝试下面的代码,GET 请求就可以正常工作:

parameters = 'token=' + token
url = base_url + '/configurations'
response = requests.get(url, params=parameters)
print(response.json())

但是,如果我为 POST 请求尝试下面的代码,我会收到错误 401:'Invalid token'

configName = 'test_create_config' + str(random.randint(0, 1000000))
configParameters = [
    {'parameter': 1, 'parameterValue': '1'},
    {'parameter': 2, 'parameterValue': '0'}
    ]
body = {
        'token': token,
        'configName': configName,
        'configParameters': configParameters
    }

url = base_url + '/configurations'
response = requests.post(url, data=body)
print(response.json())

我确定我遗漏了一些东西,但我找不到什么,因为令牌与用于获取请求的令牌相同。

编辑:请在下面找到与发布请求相对应的招摇文档:

post:
        - configurations
      summary: Create a new configuration
      description: Create a new configuration and insert it in the database.
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: query
          name: token
          description: Your token value.
          required: true
          type: string
        - in: query
          name: configName
          description: Your new configuration name.
          required: true
          type: string
        - in: query
          name: parameters
          description: Your new configuration parameter values. The payload is an array of strings '{"parameter":0,"parameterValue":"0"}' set for each parameter. In order to create it, you have to get the parameterVersion informations first.
          required: true
          type: array
          items:
            type: string
      responses:
        '200':
          description: Configuration has been created successfully.
          schema:
            type: object
            properties:
              status:
                type: string
                default: "DONE"
        '400':
          description: At least one of the request parameter is invalid and prevent the new configration creation.
        '500':
          description: Internal server error.

标签: pythonapipostpython-requests

解决方案


根据您发布的 Swagger 文档,您传递的参数应该作为 URL 查询参数 - 而不是正文。

- in: query
  name: token
  description: Your token value.
  required: true
  type: string

因此,您应该将请求更改为:

response = requests.post(url, params=body)  # params are query parameters

推荐阅读