FastAPi上传文件报错,There was an error parsing the body

文章描述了在使用Postman调用由FastAPI编写的文件接口时遇到的错误,问题在于Postman的工作目录设置和URL路径末尾缺少斜杠。解决方案包括检查Postman的工作目录,使用curl命令验证问题,以及在FastAPI的APIRouter层处理斜杠问题,通过修改APIRouter类来自动处理路径末尾的斜杠。
摘要由CSDN通过智能技术生成

问题描述

通过postman调用fastapi编写的文件接口报错,如下图:

{
    "detail": "There was an error parsing the body"
}

问题的解决过程

postman本身的问题

postman有个work directory的概念,所以再使用postman上传的文件必须在这个目录下,否则读取不到文件,导致发送给接口的数据是空数据,导致fastapi获取不到body.

还有个方法验证是不是你工具的问题,那就是通过cur的方式:

 

curl --location 'http://192.168.1.13:8000/v1/pdf/upload' \
--form 'file=@"run_test.pdf"'

 如果这个命令能成功,那说明可能是你工具的问题了。

FastAPI的问题

执行完上面的步骤还不行,那简直就是要了老命了。经过一番折腾,发现是router的配置问题,

在router的配置中,url是以 `/`结尾的,但是我的postman中没有写/,所以导致请求重定向(307),最终导致了这个报错。(具体原因,我还不太清楚,如果有老哥明白,帮忙给评论一下。)

加上/后,就能正常请求了。

 

 

怎么在框架层面处理这个问题 

可以对APIRouter进行一下处理,代码如下:

from fastapi import APIRouter as FastAPIRouter
from typing import Any, Callable
from fastapi.types import DecoratedCallable


class APIRouter(FastAPIRouter):

    def api_route(
        self, path: str, *, include_in_schema: bool = True, **kwargs: Any
    ) -> Callable[[DecoratedCallable], DecoratedCallable]:
        if path.endswith("/"):
            path = path[:-1]

        add_path = super().api_route(
            path, include_in_schema=include_in_schema, **kwargs
        )

        alternate_path = path + "/"
        add_alternate_path = super().api_route(
            alternate_path, include_in_schema=False, **kwargs
        )

        def decorator(func: DecoratedCallable) -> DecoratedCallable:
            add_alternate_path(func)
            return add_path(func)

        return decorator

使用了上面的代码就能正常处理斜杠的问题了。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值