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

2020-05-05 07:24:23 +08:00
 holinhot

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

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

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

{
  "email": "user52@example.com",
  "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": ""
}
3521 次点击
所在节点    Python
3 条回复
holinhot
2020-05-05 07:41:35 +08:00
错误返回格式看文档可以改了

```
@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
2020-05-05 07:57:05 +08:00
仔细研究已搞定
```
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
2020-05-07 01:02:51 +08:00
改了错误格式后自动生成的文档是一个应该是

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/668571

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX