将 curl 命令转换为 Python 请求

1 python python-requests

我拥有的可以正常工作的 curl 命令是 -

curl -X GET -H "Authorization: Basic <base64userpass>" -H "Content-Type: application/json" "http://<host>/bamboo/rest/api/latest/result/<plankey>.json?expand=results.result&os_authType=basic"
Run Code Online (Sandbox Code Playgroud)

在 Python 中,这就是我目前拥有的 -

   headers = {'Authorization': 'Basic <base64userpass>', 'Content-Type': 'application/json'}
   datapoints = {'expand': 'results.result', 'os_authType': 'basic'}
   url = "http://<host>/bamboo/rest/api/latest/result/<plankey>.json"
   r = requests.get(url, headers=headers, data=datapoints)
Run Code Online (Sandbox Code Playgroud)

我在使用 Python 请求时得到的响应是<Response [403]>,但是在使用 curl 时我得到了预期的数据。

我在这里缺少什么?

谢谢。

Dek*_*kel 5

您应该使用auth请求选项来进行基本身份验证。CURL 命令行为您处理了更多标头(除非您使用 ,否则请求不会处理它们auth):

>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
Run Code Online (Sandbox Code Playgroud)

或者只是使用:

>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
Run Code Online (Sandbox Code Playgroud)

(更改 URL 和所有内容)。

还要注意,requests应该得到params=(而不是data=)。