FastAPI 怎么更好的返回自定义的格式
官方文档是用 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": "" }