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
SystemLight
V2EX  ›  Python

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

  •  
  •   SystemLight ·
    SystemLight · 2021-12-16 14:13:53 +08:00 · 2097 次点击
    这是一个创建于 854 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • pydantic 可以格式化 ORM 模型,但是如何能返回列表类型
    • [Model,Model,Model] 这种格式如何通过 pydantic 验证
    3 条回复    2021-12-18 15:47:14 +08:00
    NCZkevin
        1
    NCZkevin  
       2021-12-16 14:19:49 +08:00
    from typing import List
    List[Model]
    ospider
        2
    ospider  
       2021-12-17 12:59:49 +08:00
    首先,restful 接口返回 list 不是一个最佳实践。如果你直接返回了一个 list ,翻页信息放到哪儿呢?所以最好还是返回一个特定的对象,而不是“裸” list 。比如:

    ```py
    class Item(BaseModel):
    pass

    class Res(BaseModel):
    page: int
    page_size: int
    items: list[Item]
    ```
    l4ever
        3
    l4ever  
       2021-12-18 15:47:14 +08:00
    @ospider 我更倾向于
    {
    "code": 0,
    "msg":"ok",
    "data":{
    "page":1,
    "page_size":100,
    "items":[...]
    }
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5292 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 07:39 · PVG 15:39 · LAX 00:39 · JFK 03:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.