python - Azure Devops 上传图像

标签 python azure azure-devops

我正在使用 python 将大量数据导入 Azure Devops。我已经把所有的部分都工作好了。我可以上传图像,但我的问题是当我从 Devops 网站下载图像时,它不是有效文件。我将分享我的图片上传代码。

def convertAttachmentToJsonBinary(attachmentPath):
    file = open(attachmentPath, 'rb')
    file_data = file.read()
    encoded_data = base64.b64encode(file_data)
    decoded_data = encoded_data.decode()
    data = "[" + decoded_data + "]"
    return data


def patchWorkItemWithAttachment(case_id, att_id, att_url):
    json_template = open("attachment.json", "r")
    json_data = json.load(json_template)
    json_data[0]['value']['url'] = att_url
    json_data[0]['value']['attributes']['comment'] = "Adding attachment"

    response = requests.patch(patch_workitem_url.replace("{id}", case_id), json=json_data, headers=headers)
    print(response.json())

在上传新案例时,我会创建案例、添加附件,然后使用新附件修补新创建的案例。再次完成所有这些工作。我可以在线看到我的案例中的附件,但是当我下载它时,该文件无效。 Image on Devops enter image description here

我尝试将数据读取为字节数组,如下所示:

def convertAttachmentToJsonBinary(attachmentPath):
    file = open(attachmentPath, 'rb')
    encoded_data = bytearray(file.read())

    data = "[" + str(encoded_data) + "]"
    return data

我遇到同样的错误,上传图像有效,但下载图像无效。

最佳答案

我再次测试,发现无法打开上传附件Rest API成功返回的url。所以上传时图像已损坏。

请尝试使用 bytearray(image_file.read()) 将图像转换为字节数组 .

请替换 <> 的值

import requests
import base64
from io import BytesIO

pat = 'xxx'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
url = 'https://dev.azure.com/<org_name>/<image_name>/_apis/wit/attachments?fileName=<filename.bmp>&api-version=6.0'

headers = {
    'Content-Type': 'application/octet-stream', 
    'Authorization': 'Basic '+authorization
}

#upload to attachment
with open("<image_path>", "rb") as image_file:
    # base64 doesn't work well
    # encoded_data = base64.b64encode(image_file.read())
    # decoded_data = encoded_data.decode()
    # data = "[" + decoded_data + "]"
    data = bytearray(image_file.read())

    r = requests.post(url, data=data, 
        headers=headers)

    print(r.text)

#connect wit with attachment
......

关于python - Azure Devops 上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69379698/

相关文章:

python - 为什么 Frechet 分布在 scipy.stats 和 R 中不同

javascript - Microsoft Azure CosmosDB 脚本资源管理器 console.log

azure - 使用 Bicep 模板 Azure 添加 Blob 存储的生命周期管理规则

tfs - 将测试用例连同参数和附件从 TFS 迁移到 VSTS

python - 获取 HiddenField 的值并从模板插入它 - Flask

python - Flask - Web 服务器不会在代码更改时重新加载

python - 如何在 Flask 模板上设置背景图片?

azure - 使用 U-SQL 消除某一特定列中的重复值和空值,同时保持第二列正确对齐

json - Azure 数据工厂将 JSON 复制到表中的行

azure-devops - 具有多个工件的 AzureDevOps 发布管道