首页 > 解决方案 > 将 curl 命令转换为 python 请求时遇到问题

问题描述

我正在尝试使用 API 从网站中获取一些数据,但我无法将示例 curl 命令转换为 python 请求。

示例 curl 命令

curl -X POST "some_url" \
-H "accept: application/json" \
-H "Authorization: <accesstoken>" \
-d @- <<BODY 
{} 
BODY

我的 python 请求不起作用

headers = {
    'Authorization': "Bearer {0}".format(access_token)
}

response = requests.request('GET', "some_url", 
                            headers=headers, allow_redirects=False)

我收到错误代码 400,谁能帮我找出问题所在?

标签: pythonapicurlpython-requests

解决方案


curl 的等效请求代码应为:

import requests

headers = {
    'accept': 'application/json',
    'Authorization': '<accesstoken>',
}

data = "{} "
response = requests.post('http://some_url', headers=headers, data=data)

您可以使用https://curl.trillworks.com/来转换您的实际 curl 调用(请注意,它不会处理heredocs,如您的示例中所示)。

如果您发现 curl 和您的 python 代码之间的行为不同,请转储 HTTP 请求并进行比较:


推荐阅读