首页 > 解决方案 > 使用 fastapi 和请求发布多张图片

问题描述

我想知道在使用两个图像文件作为输入时如何使用请求。

服务器

from fastapi import FastAPI, File

app = FastAPI()

@app.post("/images")
def images(img1: bytes = File(...), img2: bytes = File(...)):
    # **do something**
    return {"message": "OK"}

我成功发布了curl如下命令,

curl -X POST \
  'http://127.0.0.1:8000/images' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'img1=@<IMG1_FILE>;type=image/<EXTENSION>' \
  -F 'img2=@<IMG2_FILE>;type=image/<EXTENSION>'

但我使用如下请求的脚本失败了,得到了400 BAD Request

import requests

url = "http://127.0.0.1:8000/images"
headers = {"accept": "application/json", "content-type": "multipart/form-data"}
files = {"img1": open("img1_path.jpg", "rb"), "img2": open("img2_path.jpg", "rb")}

response = requests.post(url, headres=headers, files=files)

谁能帮我??

标签: pythonpython-requestsfastapi

解决方案


首先确保您安装了python-multipart软件包。

然后content-type从请求标头中删除,如下所示:

import requests

url = "http://127.0.0.1:8000/images"
headers = {"accept": "application/json"}
files = {"img1": open("img1_path.jpg", "rb"), "img2": open("img2_path.jpg", "rb")}

response = requests.post(url, headers=heaers, files=files)

推荐阅读