【问题标题】:Sending image over POST request with Python Requests使用 Python 请求通过 POST 请求发送图像
【发布时间】:2018-04-20 02:20:07
【问题描述】:

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

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

提前谢谢你。

编辑:另一个用户指出here 提出了类似的问题。但是,如果您查看它,我当前的代码与建议的解决方案类似,但它仍然对我不起作用。

【问题讨论】:

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


【解决方案1】:

使用这个sn-p

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)

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 2015-07-24
    • 1970-01-01
    • 2021-11-18
    • 2021-08-02
    • 2019-11-24
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多