我需要通过 FastAPI 发送文件和数据。我正在尝试发送请求但无法正常工作

I need to send files and data through FastAPI. I'm trying to send requests but couldn't get it to work

我需要通过 FastAPI 发送文件和数据。我正在尝试发送请求,但无法正常工作

例如:

服务器:

import uvicorn
from fastapi import FastAPI, File
from pydantic import BaseModel


app = FastAPI()


class Data(BaseModel):
    test1: str = None
    test2: str = None
    test3: str = None


@app.post("/uploadfile/")
async def create_file(
    data: Data,
    image: bytes = File(...),
):
    return {"postdata": len(image),
            "data": data.camera,
            }

if __name__ == "__main__":
    uvicorn.run(app)

客户:

import requests
import cv2
import json
image = cv2.imread('/marti.jpg')
data2 = cv2.imencode(".jpg", image)[1]


payload = {"test1": "value_1", "test2": "value_2", "test3": "value_3"}
files = {
    'image': ('a.jpg', data2.tobytes(), 'image/jpeg', {'Expires': '0'})
}

res = requests.post("http://localhost:8000/uploadfile/",
                    files=files, data=payload)
print(res.content)
print(res.status_code, res.json())

我得到的错误:

422 Unprocessable Entity


面对这种情况,您有什么建议?

你不能。请参阅文档 here:

You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json.

This is not a limitation of FastAPI, it's part of the HTTP protocol.

这通常可以通过期望 Form 而不是 json 来解决(请参阅此答案 here),或者通过拥有两个独立的端点来解决;一个上传照片和 returns 匹配的 ID,另一个利用该 ID 将 json 数据发送到。

您正在 JSON 正文中获得 Data

如果你想这样做,你应该这样做:

@app.post("/uploadfile/")
async def create_file(
    test1: Optional[str] = Form(None),
    test2: Optional[str] = Form(None),
    test3: Optional[str] = Form(None),
    image: bytes = File(...),
):
    # Stuff here ...  

PS: