【问题标题】:POST requests API using Python - status code 500使用 Python 的 POST 请求 API - 状态码 500
【发布时间】:2020-01-13 10:11:21
【问题描述】:

我正在用 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

【问题讨论】:

    标签: python python-3.x rest post python-requests


    【解决方案1】:

    我想出了解决办法:

    post_r = requests.post(url = POST_url, data = body, headers = header)
    

    应该改为

    post_r = requests.post(url = POST_url, json = body, headers = header)
    

    所以,我只是将 data 替换为 json 并且脚本将 post_text 输出打印出来就好了。

    header 中的 'content-type' 更改为 'application' 并没有帮助。它向我抛出了状态代码 415(“HTTP 415 Unsupported Media Type client 错误响应代码表示服务器拒绝接受请求,因为有效负载格式的格式不受支持。格式问题可能是由于请求的指示内容-Type 或 Content-Encoding ,或作为直接检查数据的结果。”)。

    我仍然想知道为什么 data = body 在 post request 行中是不可接受的。

    【讨论】:

    • 您使用的是什么版本的requests。我认为在过去,data= 期望一个包含 json 有效负载的字符串,如果您指定标头,但 json= 接受了一个字典(并且不再需要您指定标头)。但是看看最新的文档,看起来data= 现在也接受字典了...
    • 我的包版本号是 requests==2.22.0 和 requests-oauthlib==1.2.0。我认为这是一本字典,但我很想了解更多关于 data = body 不起作用的信息,特别是如果当前的文档说它可能会起作用。
    • 为您测试它的一种简单方法是尝试data=json.dumps(body) 并查看它是否有效(只要确保您的标题中仍有'content-type': 'application/json')。如果是这样,那么它是 data= 的字符串 json= 的字典。
    猜你喜欢
    • 2021-10-01
    • 1970-01-01
    • 2023-04-06
    • 2018-06-10
    • 2020-10-15
    • 2018-11-29
    • 2020-04-12
    • 1970-01-01
    • 2020-05-29
    相关资源
    最近更新 更多