跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • FastAPI 怎么更好的返回自定义的格式
未分類
29 3 月 2020

FastAPI 怎么更好的返回自定义的格式

FastAPI 怎么更好的返回自定义的格式

資深大佬 : holinhot 8

官方文档是用 response_model,但感觉 这个好像不是很灵活。

我想要返回的统一格式, 把 pydantic 的验证错误也包进自己定义的格式里

pydantic 默认数据返回格式格式:

{   "email": "[email protected]",   "id": 6,   "is_active": true,   "item": [] } 

pydantic 默认验证错误格式:

{   "detail": [     {       "loc": [         "body",         "user",         "email"       ],       "msg": "value is not a valid email address",       "type": "value_error.email"     }   ] } 

这种返回格式缺乏规范性,后面调用接口时就非常乱了。

我想要返回的统一格式统一成下面这样,方便调用和判断错误

{ "success": true, "time": "1588633541", "errors": "", "result": {   "username": "bigbig",   "created_at": "2020-05-04 21:57:22.815393" } }  { "success": false, "time": "1588633541", "errors": {   "msg": "Authorization failed",   "errors": {"detail": "wrong user name or password"} }, "result": "" }  { "success": false, "time": "1588633541", "errors": {"detail": [     {       "loc": [         "body",         "user",         "email"       ],       "msg": "value is not a valid email address",       "type": "value_error.email"     }   ]}, "result": "" } 

大佬有話說 (3)

  • 主 資深大佬 : holinhot

    错误返回格式看文档可以改了

    “`
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
    status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
    content=jsonable_encoder(
    {
    “success”: False,
    “errors”: exc.errors(),
    “result”: “”,
    “body”: exc.body
    }
    )
    )
    “`

    “`
    {
    “success”: false,
    “errors”: [
    {
    “loc”: [
    “body”,
    “user”,
    “email”
    ],
    “msg”: “value is not a valid email address”,
    “type”: “value_error.email”
    }
    ],
    “result”: “”,
    “body”: {
    “email”: “user522example.com”,
    “password”: “string”
    }
    }
    “`

    response_model 还在研究,不然就只能不用 response_model,完全自己返回 json 内容了

  • 主 資深大佬 : holinhot

    仔细研究已搞定
    “`
    class User(UserBase):
    id: int
    is_active: bool
    item: List[Item] = []

    class Config:
    orm_mode = True

    class Standard_result_format(BaseModel):
    success: bool = True
    errors: list = []
    result: User
    “`

    是可以在下面调用另一下 BaseModel class

  • 主 資深大佬 : holinhot

    改了错误格式后自动生成的文档是一个应该是

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具