我目前正在尝试将Python(3.5)与Requests库一起发送POST请求。此POST将发送一个图像文件。以下是示例代码:
import requests
url = "https://api/address"
files = {'files': open('image.jpg', 'rb')}
headers = {
'content-type': "multipart/form-data",
'accept': "application/json",
'apikey': "API0KEY0"
}
response = requests.post(url, files=files, headers=headers)
print(response.text)
但是,当我运行代码时,我收到400错误。我设法到达API端点,但在响应中它声明我无法发送任何文件。
{
"_id": "0000-0000-0000-0000",
"error": "Invalid request",
"error_description": "Service requires an image file.",
"processed_time": "Tue, 07 Nov 2017 15:28:45 GMT",
"request": {
"files": null,
"options": {},
"tenantName": "name",
"texts": []
},
"status": "FAILED",
"status_code": 400,
"tenantName": "name"
}
“files”字段显示为null,这对我来说有点奇怪。 POST请求适用于Postman,我使用相同的标头参数并使用“form-data”选项将图像添加到正文(请参阅Screenshot)。
这里有什么我想念的吗?有没有更好的方法通过POST发送图像文件与python?
先感谢您。
编辑:一个类似的问题被另一个用户指出here。但是,如果你研究它,我当前的代码与建议的解决方案类似,但它仍然不适合我。
使用此代码段
import os
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
name_img= os.path.basename(path_img)
files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
with requests.Session() as s:
r = s.post(url,files=files)
print(r.status_code)