使用Python请求通过POST请求发送图像

时间:2017-11-07 15:47:23

标签: python python-3.x post python-requests postman

我目前正在尝试将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"
}

"文件"字段显示为空,这对我来说似乎有点奇怪。 POST请求适用于Postman,我使用相同的标题参数并使用" form-data"将图像添加到正文中。选项(见Screenshot)。

我在这里缺少什么吗?有没有更好的方法通过POST发送图像文件与python?

提前谢谢。

编辑:另一位用户指出了一个类似的问题here。但是,如果你研究一下,我现在的代码与建议的解决方案类似,但它对我来说仍然没有用。

1 个答案:

答案 0 :(得分:1)

使用此代码段

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)