发送多部分/表单数据的问题

2024-10-02 14:30:07 发布

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

我正试图利用BIMTrack的restapi发布一个图像。要做到这一点,API要求我在图像之前发送一个json文件,这本身就需要多部分/表单数据

json填充失败后将遇到错误代码:415和错误消息:The content-type of the first file of the request must be application\json

我已经使用Postman&;的web调试代理成功地发出了这个post请求;Fiddler,但我无法在python请求中重复我的成功

Python代码(这不起作用):

image = r"C:\Users\aflemming\Desktop\Images\DBMICon.png"
jsonFile = r"C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json"

headers = {'Authorization' : 'Bearer <MyToken>'}

files = {
    'Json': (None, open(jsonFile, 'rb'), 'application/json'),
    'Image': (None, open(image, 'rb'), 'image/png')
}

r = requests.post(https://api.bimtrackapp.co/v3/hubs/07La7cOZ/projects/20767/issues/3161484/viewpoints, files=files, headers=headers)

提琴手原始请求(此操作有效):

User-Agent:Fiddler Everywhere
Authorization:Bearer eb5e3983a7546dad76067418ff93175ef42b816dd57f78f54101f0b63862542e
Host:api.bimtrackapp.co
Content-Length:11322
Content-Type:multipart/form-data;boundary=-------------------------acebdf13572468

---------------------------acebdf13572468
Content-Disposition: form-data; name="description" 
the_text_is_here
---------------------------acebdf13572468
Content-Disposition: form-data; name="jsonfile"; filename="myjson.json"
Content-Type: application/json

<@INCLUDE *C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="image"; filename="DBMICon.png"
Content-Type: image/png

<@INCLUDE *C:\Users\aflemming\Desktop\Images\DBMICon.png*@>
---------------------------acebdf13572468--

邮递员请求(这同样有效): enter image description here

enter image description here

BIMTrack的restapi:https://api.bimtrackapp.co/swagger/ui/index

我很乐意在需要时提供更多信息


Tags: theimageformjsondataapplicationpngcontent
1条回答
网友
1楼 · 发布于 2024-10-02 14:30:07

我通过改变request方法(使用requests.request over requests.post)并设置verify=False参数找到了一个解决方案

似乎请求遇到了一个SSLCertVerificationError,绕过证书解决了这个问题

最终代码:

image = r"C:\Users\aflemming\Desktop\Images\DBMICon.png"
jsonFile = r"C:\Users\aflemming\source\repos\IfcOpenShell\IfcOpenShell\BIM\myjson.json"
url = "https://api.bimtrackapp.co/v3/hubs/07La7cOZ/projects/20767/issues/3161484/viewpoints"

files = [
    ('Json', ('Json2', open(jsonFile,'rb'), 'application/json')),
    ('Image', ('Image2', open(image,'rb'), 'image/png'))
]

headers = {
    'Authorization': 'Bearer <MyToken>'
}

response = requests.request("POST", url, headers=headers, files = files, verify=False)

相关问题 更多 >