python - 使用 Python 的 POST 请求
问题描述
我正在尝试使用 Python 发布一个简单的 POST 请求,但我收到了意外的错误消息。
文档示例如下:
- GET /configurations : 获取配置列表
- 参数:令牌(字符串)
- POST /configurations :发布新配置
- 参数:token(字符串)、configName(字符串)、configParameters(数组)
如果我尝试下面的代码,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.
解决方案
根据您发布的 Swagger 文档,您传递的参数应该作为 URL 查询参数 - 而不是正文。
- in: query
name: token
description: Your token value.
required: true
type: string
因此,您应该将请求更改为:
response = requests.post(url, params=body) # params are query parameters
推荐阅读
- python-3.x - Jupyter Notebook 不会出现情节
- swift - @final 关键字的使用
- c++ - Inconsistent behavior with returning a vector in c++
- search - 使用 awk 从多个文件中提取数据
- php - 如何从数据库行中获取项目列表并在 Laravel 中返回列表?
- javascript - 编辑 iframe 的 css(soundcloud 嵌入式播放器)
- java - 原因:jarsigner.exe 失败,退出代码为 1:jarsigner:
- php - Laravel 将路由参数修改为 name 列而不是 id
- php - How to use symfony environments dev and prod
- android - Cannot find a version of 'com.android.support:appcompat-v7' that satisfies the version constraints