python - 使用 Python 的 POST 请求 API - 状态码 500
问题描述
我正在用 Python(3.7.4,Windows 10)为 POST 请求(REST API)编写脚本,对象是从另一个数据库检索数据并将其移动到另一个数据库。
from os import getenv
import requests
# header includes login credentials and content type
header = {'access_key': "key", "access_token": getenv("token1"), 'content-type': 'application/json'}
# Body includes table names and other specified data to retrieve
body = {
# table names etc.
}
# Post request and printing of the post request text
post_r = requests.post(url = POST_url, data = body, headers = header)
post_text = post_r.text
print(post_text)
这会抛出一个 HTTP 错误状态代码 500。我应该在代码中进行哪些更改才能正确打印post_text?
解决方案
我想出了解决方案:
post_r = requests.post(url = POST_url, data = body, headers = header)
应该改为
post_r = requests.post(url = POST_url, json = body, headers = header)
所以,我只是用json替换了数据,脚本打印了post_text输出就好了。
将标头中的'content-type'更改为'application'并没有帮助。它向我抛出了状态代码 415(“HTTP 415 Unsupported Media Type client 错误响应代码表明服务器拒绝接受请求,因为有效负载格式的格式不受支持。格式问题可能是由于请求指定的 Content-Type 或Content-Encoding ,或者直接检查数据的结果。”)。
我仍然想知道为什么data = body在发布请求行中是不可接受的。
推荐阅读
- laravel-8 - xxx 类包含 1 个抽象方法,因此必须声明为抽象方法或实现其余方法 App\Models\xxx::getActivitylogOptions
- kubernetes - 如何将声明用作卷
- firebase - 没有为类型“QuerySnapshot”Cloud Firestore 更新定义吸气剂“文档”
- valueerror - 我该如何解决:[ValueError:int() 以 10 为底的无效文字:]
- reactjs - React.js 挂钩状态未更新
- mongodb - MongoDB如何使用基于另一个字段的相同键从同一集合中获取文档
- c# - DotNetCore 路由属性扩展 url
- android - 我的 Sqlite To Listview 有什么问题,它没有显示所需的结果
- reactjs - 反应,地图组件,意外结果
- python-3.x - 从 python 请求上传时,Django 文件对象总是 0 字节