美文网首页
在JSONResponse里使用BaseModel 报错Obje

在JSONResponse里使用BaseModel 报错Obje

作者: RedB | 来源:发表于2022-01-17 19:54 被阅读0次

问题描述

最近在学习使用FastApi。我仿照https://fastapi.tiangolo.com/zh/tutorial/handling-errors/#_4 ,自定义了一个自定义异常处理器,并且在其return JSONResponse中,为content赋值了一个BaseModel对象。

...
raise CustomHTTPException(status.HTTP_200_OK, ErrorRespBody(...))
...
async def unicorn_exception_handler(request: Request, exception: CustomHTTPException):
    return JSONResponse(
        status_code=exception.status_code,
        content=exception.resp_model
    )

然后就报错了
Object of type ErrorRespBody is not JSON serializable

错误原因

查看JSONResponse的源码,会发现它会调用json.dumps(),而json.dumps()只能处理str、dict、list等基本类型,所以需要将content=后面的对象转成dict类型。

解决方法

只需要使用官方文档中提到的base_model.dict()方法即可,https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict

最终代码为:

async def unicorn_exception_handler(request: Request, exception: CustomHTTPException):
    return JSONResponse(
        status_code=exception.status_code,
        content=exception.resp_model.dict()
    )

相关文章

网友评论

      本文标题:在JSONResponse里使用BaseModel 报错Obje

      本文链接:https://www.haomeiwen.com/subject/gjachrtx.html