【问题标题】:FastApi Post Request With Bytes Object Got 422 Error带有字节对象的 FastApi 发布请求得到 422 错误
【发布时间】:2021-08-08 13:28:35
【问题描述】:

我正在编写一个带有字节正文的 python 发布请求:

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"}]}

那么我的代码哪里出了问题,我应该如何修复它? 提前谢谢大家帮忙!!

【问题讨论】:

    标签: python python-requests fastapi


    【解决方案1】:

    默认情况下,FastAPI 将期望您传递 json,该 json 将解析为 dict。如果它不是 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
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-05-12
        • 2023-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-04
        • 2021-04-13
        • 2021-10-02
        • 1970-01-01
        相关资源
        最近更新 更多