FastApi Post 字节对象请求出现 422 错误

FastApi Post Request With Bytes Object Got 422 Error

我正在写一个 python post 带有字节主体的请求:

with open('srt_file.srt', 'rb') as f:
    data = f.read()

    res = requests.post(url='http://localhost:8000/api/parse/srt',
                        data=data,
                        headers={'Content-Type': 'application/octet-stream'})

在服务器部分,我尝试解析正文:

app = FastAPI()
BaseConfig.arbitrary_types_allowed = True


class Data(BaseModel):
    data: bytes

@app.post("/api/parse/{format}", response_model=CaptionJson)
async def parse_input(format: str, data: Data) -> CaptionJson:
    ...

但是,我得到了 422 错误: {"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}

那么我的代码哪里出了问题,我该如何解决呢? 预先感谢大家的帮助!!

如果您请求的最终目标是仅发送字节,那么请查看 FastAPI 的文档以接受类似字节的对象:https://fastapi.tiangolo.com/tutorial/request-files.

无需将字节包含在模型中。

默认情况下,FastAPI 希望您传递 json,这将解析为字典。如果它不是 json,它就不能这样做,这就是为什么你会看到你看到的错误。

您可以使用 Request 对象来接收来自 POST 正文的任意字节。

from fastapi import FastAPI, Request

app = FastAPI()

@app.get("/foo")
async def parse_input(request: Request):
    data: bytes = await request.body()
    # Do something with data

您可以考虑使用 Depends,这样您就可以清理路由函数。 FastAPI 将首先调用您的依赖函数(在此示例中为 parse_body)并将其作为参数注入到您的路由函数中。

from fastapi import FastAPI, Request, Depends

app = FastAPI()

async def parse_body(request: Request):
    data: bytes = await request.body()
    return data


@app.get("/foo")
async def parse_input(data: bytes = Depends(parse_body)):
    # Do something with data
    pass