gpt4 book ai didi

python - 如何在 python3 和 `requests` 上发布图像和文本 MultipartForm ?

转载 作者:行者123 更新时间:2023-12-03 09:01:07 25 4
gpt4 key购买 nike

我正在将代码从 NodeJS 移植到 python3。我想发布图像二进制数据和文本。我该怎么做 ?谢谢。

NodeJS

filePath = "xxx.jpeg"
text = "xxx"
return chakram.request("POST", "http://xxx",
{ "multipart" : [
{ "body" : fs.createReadStream(filePath),
"Content-Type" : "image/jpeg",
"Content-Disposition" : "name='file'; filename='" + filePath + "'"
},
{ "body" : JSON.stringify(this.RequestData(text)),
"Content-Type" : "application/specified-content-type-xxx"
}
],
"headers" : {
"Authorization" : "xxx"
}
})

我的错误Python代码与请求:

filePath = "xxx.jpeg"
text = "xxx"
headers = {
"Authorization" : "xxx"
}

binary_data = None
with open(file_path, 'rb') as fp:
binary_data = fp.read()

request_body = {
"text": text,
"type": "message",
"from": {
"id": "user1"
}
}
files = {
"file": (filePath, binary_data, 'image/jpeg'),
"": ("", request_body, "application/specified-content-type-xxx")
}
resp = requests.post("http://xxx", files=files, headers=headers)

我收到 500 错误。

最佳答案

python3 请求模块支持文件,here 。这应该适合您。

import requests

url = "http://xxx"

# just set files to a list of tuples of (form_field_name, file_info)
multiple_files = [
('images', ('xxx.jpeg', open('xxx.jpeg', 'rb'), 'image/png')),
('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))
]

text_data = {"key":"value"}
headers = {
"Authorization" : "xxx",
"Content-Type": "application/json"
}
r = requests.post(url, files=multiple_files, data=text_data, headers=headers)
r.text

关于python - 如何在 python3 和 `requests` 上发布图像和文本 MultipartForm ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50225264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com