无效 Json 错误,当 Uploading/pushing 一个文件使用 Pushes Create Api with Python 到 Azure Devops Repo

Invalid Json error when Uploading/pushing a file to Azure Devops Repo using Pushes Create Api with Python

我试图自动执行将一些文件推送到存储库中的各个文件夹的任务。我尝试使用 azure 提供的 Rest API。当使用 Pushes Create API 时,从文档中这是请求正文中的内容

snapshot of request body

这是我写的 python 代码的快照:

The code that I am using

在上面的代码中repositeries_url包含有效的APIURL。 当我 运行 代码时,我得到响应代码 400 并打印 JSON 给我

{'$id': '1', 'innerException': None, 'message': 'The body of the request contains invalid Json.\r\nParameter name: contentStream', 'typeName': 'Microsoft.TeamFoundation.SourceControl.WebServer.InvalidArgumentValueException, Microsoft.TeamFoundation.SourceControl.WebServer' , 'typeKey': 'InvalidArgumentValueException', 'errorCode': 0, 'eventId': 0}

为什么会出现这个错误,我该如何纠正这个错误?

我发现您的 python 代码中存在以下错误。

在您的代码中,您将 payload["commits"] 定义为提交数组。

但是您错误地将 temp 指定为它的值。您需要将 temp 附加到 payload["commits"] 数组。 IE。 payload["commits"].append(temp)

此外,如果您想在 request.post 方法中使用 json 来 post 数据。您可以直接传递 payload 对象。如下所示:

response = requests.post(url = repo_url, json = payload, headers = header)

或者您可以使用 request.post 方法中的 data 来 post json 字符串。见下文:

response = requests.post(url = repo_url, data= jsonPayload, headers = header)

完整代码见下方:

....    
temp["changes"].append(aksh)
payload["commits"].append(temp)  ##append temp to commits array
jsonPayload=json.dumps(payload)

#pass payload to json parameter directly
response = requests.post(url = repo_url, json= payload, headers = header)
#you can also use data
#response = requests.post(url = repo_url, data= jsonPayload, headers = header)