官方文档是用 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": ""
}
1
holinhot OP 错误返回格式看文档可以改了
``` @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 内容了 |
2
holinhot OP 仔细研究已搞定
``` 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 |
3
holinhot OP 改了错误格式后自动生成的文档是一个应该是
|