V2EX = way to explore
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
V2EX  ›  Python

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

  •  
  •   holinhot · 2020-05-05 07:24:23 +08:00 · 3536 次点击
    这是一个创建于 1670 天前的主题,其中的信息可能已经有所发展或是发生改变。

    官方文档是用 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 条回复    2020-05-07 01:02:51 +08:00
    holinhot
        1
    holinhot  
    OP
       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
        2
    holinhot  
    OP
       2020-05-05 07:57:05 +08:00   ❤️ 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
       2020-05-07 01:02:51 +08:00
    改了错误格式后自动生成的文档是一个应该是
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2599 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 11:20 · PVG 19:20 · LAX 03:20 · JFK 06:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.