FastAPI 怎么更好的返回自定义的格式 - V2EX
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
holinhot

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

  •  
  •   holinhot May 5, 2020 4055 views
    This topic created in 2198 days ago, the information mentioned may be changed or developed.

    官方文档是用 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 replies    2020-05-07 01:02:51 +08:00
    holinhot
        1
    holinhot  
    OP
       May 5, 2020
    错误返回格式看文档可以改了

    ```
    @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
        2
    holinhot  
    OP
       May 5, 2020   1
    仔细研究已搞定
    ```
    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
        3
    holinhot  
    OP
       May 7, 2020
    改了错误格式后自动生成的文档是一个应该是
    About     Help     Advertise     Blog     API     FAQ     Solana     3360 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 560ms UTC 13:46 PVG 21:46 LAX 06:46 JFK 09:46
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86