Python POST 带图片的请求

Python POST Request with an Image

我正在尝试使用 python 向我的 Flask 网络服务器请求图像,但无法正常工作。

使用 cURL 很简单:

curl -XPOST -F "file=@image.jpg" http://127.0.0.1:5001

但在 python 中使用我的代码:

import requests

with open("image.jpg", "rb") as a_file:
  file_dict = {"image.jpg": a_file}
  response = requests.post("http://127.0.0.1:5001", files=file_dict)
  print(response.text)
  print(response.status_code)

我只是得到返回网站的 HTML 和状态 200。不是 returns 使用 cURL 的 JSON(这是我想要返回的)。

任何帮助将不胜感激,谢谢。

您可以使用下面的代码

files = {'file': open('image.jpg', 'rb')}
 
r = requests.post('http://127.0.0.1:5001', files=files)
print(r.text)