python - 使用 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)
谁能帮我??
解决方案
首先确保您安装了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)
推荐阅读
- android - 将 Android 库作为依赖项私下发布
- javascript - 我们如何创建像 toLowerCase 方法这样的javascript方法
- javascript - 传递的 id 未定义,错误 400(错误请求)
- python - 基于数组字段的MongoDB查找查询
- docker - “docker run --rm -v”从守护进程获取错误响应:状态码不正常,但 500
- c# - 升级我的 Chrome 后,除了 Bootstrap Datepicker 之外还有两个黑点
- c++ - 如何使用 PJSIP 更改 INVITE SDP 中的 RTP 媒体流地址?
- html - 两个并排可滚动的 div,水平滚动始终可见
- plugins - Gatsby createSchemaCustomization 向每个节点添加自定义字段
- powershell - Get-ADUser -LDAPFilter 使用 AND 和 OR