我想使用 bitbucket 的 rest api 创建一个提交。至此,所有关于
Response 415
的问题的答案都通过设置header中的Content-Type
为application/json;charset-UTF8
解决了。但是,这并不能解决我得到的回复。
所以这就是我想要做的:
import requests
def commit_file(s, path, content, commit_message, branch, source_commit_id):
data = dict(content=content, message=commit_message, branch=branch, sourceCommitId=source_commit_id)
r = s.put(path, data=data, headers={'Content-type': 'application/json;charset=utf-8'})
return r.status_code
s = requests.Session()
s.auth = ('name', 'token')
url = 'https://example.com/api/1.0/projects/Project/repos/repo/browse/file.txt'
file = s.get(url)
r = commit_file(s, url, file.json() , 'Commit Message', 'test', '51e0f6faf64')
GET
请求成功返回文件,我想将其内容提交到确实存在的分支test
上。
无论
Content-Type
,反应的status_code
都是415
.
这是放置请求的标题:
OrderedDict([('user-agent', ('User-Agent', 'python-requests/2.21.0')), ('accept-encoding', ('Accept-Encoding', 'gzip, deflate')), ('accept', ('Accept', '*/*')), ('connection', ('Connection', 'keep-alive')), ('content-type', ('Content-type', 'application/json;charset=utf-8')), ('content-length', ('Content-Length', '121')), ('authorization', ('Authorization', 'Basic YnVybWF4MDA6Tnp...NkJqWGp1a2JjQ3dNZzhHeGI='))])
这解释了 curl 的用法以及文件何时在本地可用。如上所示检索文件内容时,正确的请求在 python 中看起来如何?
这是使用
MultipartEncoder
的解决方案:
import requests
import requests_toolbelt.multipart.encoder
def commit_file(s, path, content, commit_message, branch, source_commit_id):
data = requests_toolbelt.MultipartEncoder(
fields={
'content': content,
'message': commit_message,
'branch': branch,
'sourceCommitId': source_commit_id
}
)
r = s.put(path, data=data, headers={'Content-type': data.content_type})
内容类型
application/json;charset=utf-8
不正确。
根据文档,您必须发送多部分表单数据。你不能使用 JSON。
此资源接受 PUT 多部分表单数据,将文件包含在名为
. 的表单字段中content
参见:How to send a "multipart/form-data" with requests in python?
我通过在标题中添加
'Content-Type': '*/*'
和 'accept': '*/*'
来解决这个问题。