虽然Createattachment&Upload attachment API成功,但在azure devops repos分支中仍然无法看到上载的文件

2024-04-24 00:40:14 发布

您现在位置:Python中文网/ 问答频道 /正文

经过大量的努力,最终在下面的代码框架中通过RESTAPI与Azure Devops交互,但在Azure Devops-Repos的分支中看不到文件

首先使用以下API创建了一个附件:

https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-rest-6.0

## Create attachment ###########################################
ado_req_headers_ATT = {"Content-Type":"application/octet-stream"}

directory_path = str('C:\\Users\\XXX\\YYY')
txt_files = [f for f in os.listdir(directory_path) if f.endswith('.json')]
if len(txt_files) != 1:
    raise ValueError('should be only one json file in the current directory')
else:
    file_name = txt_files[0]
print("Test_file",file_name)
file_path = directory_path+"\\"+str(file_name)
with open(file_path, "rb") as f:
    Test_file=f.read()
print(len(Test_file))
create_attach_url = str(organization_url)+str('/_apis/wit/attachments?fileName=')+file_name+str('&uploadType=Simple&api-version=6.0')
create_attach_details = requests.post(url=create_attach_url,headers=ado_req_headers_ATT,data=Test_file,auth=('',ADO_AUTH_PAT))
attachment_obj = create_attach_details.json()
print("create_attach_details_ID_:-",attachment_obj['id'])  ## Got attachment ID
print("create_attach_details_URL_:-",attachment_obj['url']) ## Got Url, when this url get hit in browser, got the attachment to get download.
print("Attachment_details_Status_Code:-",create_attach_details.status_code) # code: 201

随后使用以下API上传了附件:

https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/upload%20chunk?view=azure-devops-rest-6.0

## upload attachment ###########################################

CL=len(Test_file)
Range=(f'"Content-Range":"bytes 0-{CL-1}/{CL}"')
ado_req_headers_ATT = str('{"Content-Type":"application/octet-stream","Content-Length":"')+str(CL)+str('"')+str(',')+Range+str('}')
ado_req_headers_ATT=json.loads(ado_req_headers_ATT)
print(ado_req_headers_ATT)
upload_attach_url = str(organization_url)+str('/_apis/wit/attachments/')+str(attachment_obj['id'])+str('?api-version=6.0')
print(upload_attach_url)
upload_attach_details = requests.put(url=upload_attach_url,headers=ado_req_headers_ATT,data=Test_file,auth=('',ADO_AUTH_PAT))
print(upload_attach_details)
attachment_obj = upload_attach_details.json()
print(attachment_obj)
print("Attachment_details:-",create_attach_details.text)
##print("create_attach_details_ID_:-",attachment_obj['id'])  ## Got attachment ID
##print("create_attach_details_URL_:-",attachment_obj['url']) ## Got Url, when this url get hit in browser, got the attachment to get download.
print("Attachment_upload_Status_Code:-",create_attach_details.status_code)## Code: 201

这两个API都很有用,但仍然无法在azure devops Repos分支中看到该文件。我遗漏了什么,无法理解或发布API需要达到的要求?请建议

之后,我尝试使用以下API更新工作项:

https://docs.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.0#add-an-attachment

##### Update Attachment in path #######################################
ado_req_headers_ATT = {"Content-Type":"application/json-patch+json","dataType":"application/json-patch+json",}
update_attach_url = str(organization_url)+str('/_apis/wit/workitems/')+str(attachment_obj['id'])+str('?api-version=6.0')
print(update_attach_url)
#Body_data = [{"op": "test","path": "/ref","value": 3},{"op": "add","path": "/heads/branchname","value": "Adding the necessary spec"},{"op": "add","path": "/relations/-","value": {"rel": "AttachedFile","url": attachment_obj['url'],"attributes": {"comment": "Spec for the work"}}}]
Body_data = [{"op": "add","path": ref/headers/banchname,"value": {"rel": "AttachedFile","url": str(attachment_obj['url'])+str('?fileName=')+file_name,"attributes": {"comment": "Spec for the work"}}}]
Body_data = json.dumps(Body_data)
print(Body_data)
update_attach_details = requests.patch(url=update_attach_url,headers=ado_req_headers_ATT,data=Body_data,auth=('',ADO_AUTH_PAT))
print(update_attach_details.text) ## Page not found
print(update_attach_details.status_code)  ## 404

有什么建议吗


Tags: pathjsonobjurlattachmentcreatedetailsreq
2条回答

以下两个API的ie足以将文件上载到存储库:

######## Get   last commit ID ##########################
#Get_commit_url = str(organization_url)+str('/_apis/git/repositories/')+str(Repos_obj['value'][0]['id'])+str('/commits?api-version=6.0')
Get_commit_url = str(organization_url)+str('/_apis/git/repositories/')+str(Repos_obj['value'][Repository_ID]['id'])+str('/commits?api-version=6.0')
print(Get_commit_url)
Get_commit_Details = requests.get(url=Get_commit_url,headers=ado_req_headers_ATT,auth=('',ADO_AUTH_PAT))
##print(Get_Push_Details.text)
##print(Get_Push_Details.status_code)
Get_commit_Details=Get_commit_Details.json()
print(Get_commit_Details)
for item in Get_commit_Details["value"]:
    print( item["commitId"])
    old_objectID= item["commitId"]
    break

## Run push API

ado_req_headers_ATT = {"Content-Type":"application/json-patch+json"}
push_file_url = str(organization_url)+str('/_apis/git/repositories/')+str(Repos_obj['value'][Repository_ID]['id'])+str('/pushes?api-version=6.0')
print(push_file_url)
##Body_data = {"refUpdates": [{"name": Repos_obj['value'][0]['defaultBranch'],"oldObjectId":"0000000000000000000000000000000000000000"}],"commits":[{"comment": "Initial Commmit.","changes":[{"changeType": "add","item": {"path":"/Hello.doc"},"newContent": {"content": "# Tasks\n\n* Item 1Hello\n* Item 2","contentType": "rawtext"}}]}]}
Body_data = {"refUpdates": [{"name": Repos_obj['value'][Repository_ID]['defaultBranch'],"oldObjectId":old_objectID}],"commits":[{"comment": "Initial Commmit.","changes":[{"changeType": "add","item": {"path":"/Hello.doc"},"newContent": {"content": "# Tasks\n\n* Item 1Hello\n* Item 2","contentType": "rawtext"}}]}]}
##Body_data = {"refUpdates": [{"name": Repos_obj['value'][Repository_ID]['defaultBranch'],"oldObjectId":old_objectID}],"commits":[{"comment": "Remove file.","changes":[{"changeType": "delete","item": {"path":"/Hello.doc"}}]}]}
Body_data = json.dumps(Body_data)
##print(Body_data)
Push_file= requests.post(url=push_file_url,headers=ado_req_headers_ATT,data=Body_data,auth=('',ADO_AUTH_PAT))
print(Push_file.status_code)
print(Push_file.text)

我终于成功了!!!谢谢大家的支持

使用工作项附件API“Upload Chunk”时,请求方法是PUT,而不是PATCH

请将请求方法更改为PUT以查看Python代码是否可以工作

此外,请确保在API“Create”和“Upload Chunk”上使用了媒体类型“application/octet-stream

相关问题 更多 >