【发布时间】:2019-05-01 13:32:26
【问题描述】:
我正在尝试使用 REST API 将附件上传到 Azure DevOps 中的工作项。但是,虽然我可以将附件“上传”并附加到工作项,但无论是在 UI 中还是在我下载附件时,附件的大小始终为 0KB。
API 看起来相当简单,我使用过的其他十几个 API 都没有遇到过问题。我只是不知道这是哪里出了问题。这是我为此使用的代码:
import os
import sys
import requests
_credentials = ("user@example.com", "password")
def post_file(url, file_path, file_name):
file_size = os.path.getsize(file_path)
headers = {
"Accept": "application/json",
"Content-Size": str(file_size),
"Content-Type": "application/octet-stream",
}
request = requests.Request('POST', url, headers=headers, auth=_credentials)
prepped = request.prepare()
with open(file_path, 'rb') as file_handle:
prepped.body = file_handle.read(file_size)
return requests.Session().send(prepped)
def add_attachment(path_to_attachment, ticket_identifier):
filename = os.path.basename(path_to_attachment)
response = post_file(
f"https://[instance].visualstudio.com/[project]/_apis/wit/attachments?uploadType=Simple&fileName={filename}&api-version=1.0",
path_to_attachment,
filename
)
data = response.json()
attachment_url = data["url"]
patch_result = requests.patch(
f"https://[instance].visualstudio.com/[project]/_apis/wit/workitems/{ticket_identifier}?api-version=4.1",
auth=_credentials,
headers={
"Accept": "application/json",
"Content-Type": "application/json-patch+json",
},
json=[
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": attachment_url
},
}
]
)
print(patch_result)
print(patch_result.text)
add_attachment(sys.argv[1], sys.argv[2])
我已经尝试设置/删除/更改我能想到的每个可能的标头值。我试过使用requests 中post 方法上的files 属性(但因为它设置了Content-Disposition 而放弃了它,但我见过的所有示例都没有使用它),我试过了设置区域路径参数,我已经尝试了我能想到的一切,但没有任何区别。
我什至使用 Fiddler 来观察实际站点是如何进行的,然后将标头复制到 Python 中的新请求中并发送它,而我仍然看到 0kb 的结果。
在这一点上我几乎没有想法,所以如果有人知道我可能哪里出错了,将不胜感激!
【问题讨论】:
标签: python python-requests azure-devops azure-devops-rest-api