V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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
SystemLight
V2EX  ›  Python

fastapi+pydantic+sqlalchemy 如何返回列表数据?

  •  
  •   SystemLight ·
    SystemLight · Dec 16, 2021 · 3084 views
    This topic created in 1597 days ago, the information mentioned may be changed or developed.
    • pydantic 可以格式化 ORM 模型,但是如何能返回列表类型
    • [Model,Model,Model] 这种格式如何通过 pydantic 验证
    3 replies    2021-12-18 15:47:14 +08:00
    NCZkevin
        1
    NCZkevin  
       Dec 16, 2021
    from typing import List
    List[Model]
    4BVL25L90W260T9U
        2
    4BVL25L90W260T9U  
       Dec 17, 2021   ❤️ 1
    首先,restful 接口返回 list 不是一个最佳实践。如果你直接返回了一个 list ,翻页信息放到哪儿呢?所以最好还是返回一个特定的对象,而不是“裸” list 。比如:

    ```py
    class Item(BaseModel):
    pass

    class Res(BaseModel):
    page: int
    page_size: int
    items: list[Item]
    ```
    luckyc
        3
    luckyc  
       Dec 18, 2021
    @ospider 我更倾向于
    {
    "code": 0,
    "msg":"ok",
    "data":{
    "page":1,
    "page_size":100,
    "items":[...]
    }
    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2458 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 02:40 · PVG 10:40 · LAX 19:40 · JFK 22:40
    ♥ Do have faith in what you're doing.