使用 python 请求时,Bitbucket API returns 'Bad request'
Bitbucket API returns 'Bad request' when using python requests
我想向 Bitbucket API 发出创建存储库的请求。
以下卷曲有效:
curl -v -X POST -d '{"scm": "git", "is_private": "true", "fork_policy": "no_forks", "project": {"key": "MARS"}}' -H "Content-Type: application/json" https://api.bitbucket.org/2.0/repositories/myteam/test -u <user-name>
所以我在 python 中使用请求进行了相同的尝试:
data = {'scm': 'git', 'is_private': 'true', 'fork_policy': 'no_forks', 'project': {'key': 'MARS'}}
auth=(user, password)
headers = {"Content-Type": "application/json"}
url = "https://api.bitbucket.org/2.0/repositories/myteam/test"
res = requests.post(url, data=data, headers=headers, auth=auth)
但是 res
returns 'Bad request' (400)。为什么?
从您的 curl
请求可以明显看出 Bitbucket 正在接受 JSON-编码的 POST 数据。
使用 requests
作为表单编码数据发送数据会导致 HTTP 错误 400 错误请求。
为了发送 JSON-编码的 POST 数据,使用:
requests.post(url, json=data, headers=headers, auth=auth)
参考:
http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests
我想向 Bitbucket API 发出创建存储库的请求。 以下卷曲有效:
curl -v -X POST -d '{"scm": "git", "is_private": "true", "fork_policy": "no_forks", "project": {"key": "MARS"}}' -H "Content-Type: application/json" https://api.bitbucket.org/2.0/repositories/myteam/test -u <user-name>
所以我在 python 中使用请求进行了相同的尝试:
data = {'scm': 'git', 'is_private': 'true', 'fork_policy': 'no_forks', 'project': {'key': 'MARS'}}
auth=(user, password)
headers = {"Content-Type": "application/json"}
url = "https://api.bitbucket.org/2.0/repositories/myteam/test"
res = requests.post(url, data=data, headers=headers, auth=auth)
但是 res
returns 'Bad request' (400)。为什么?
从您的 curl
请求可以明显看出 Bitbucket 正在接受 JSON-编码的 POST 数据。
使用 requests
作为表单编码数据发送数据会导致 HTTP 错误 400 错误请求。
为了发送 JSON-编码的 POST 数据,使用:
requests.post(url, json=data, headers=headers, auth=auth)
参考:
http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests