FastApi Post Request With Bytes Object Got 422 Error



我正在写一个python post request with a bytes body:

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默认会期望你传递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

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

不需要在模型中包含字节。

最新更新