阅读 78

FastAPI(11)- 函数参数类型是列表,但不使用 typing 中的 List,而使用 list,会怎么样?

使用 typing 中的 List、Set、Tuple 的栗子

from typing import Optional

import uvicorn
from fastapi import FastAPI, Body
from typing import List, Tuple, Set

app = FastAPI()


@app.put("/items/{item_id}")
async def update_item(
        list_: List[int] = Body(...),
        tuple_: Tuple[int] = Body(...),
        set_: Set[int] = Body(...),
):
    results = {"list_": list_, "tuple_": tuple_, "set_": set_}
    return results


if __name__ == "__main__":
    uvicorn.run(app="9_typing:app", host="127.0.0.1", port=8080, reload=True, debug=True)

 

期望得到的请求体

{
    "list_": [
        0,
        1
    ],
    "tuple_": [
        0,
        2
    ],
    "set_": [
        0,
        3
    ]
}

  

假设里面的元素传了非 int 且无法自动转换成 int

  • typing 的 List、Set、Tuple 都会指定里面参数的数据类型
  • 而 FastAPI 会对声明了数据类型的数据进行数据校验,所以会针对序列里面的参数进行数据校验
  • 如果校验失败,会报一个友好的错误提示

 

使用 list、set、tuple 的栗子

用 Python 自带的 list、set、tuple 类,是无法指定序列里面参数的数据类型,所以 FastAPI 并不会针对里面的参数进行数据校验

@app.put("/items/{item_id}")
async def update_item(
        list_: list = Body(...),
        tuple_: tuple = Body(...),
        set_: set = Body(...),
):
    results = {"list_": list_, "tuple_": tuple_, "set_": set_}
    return results

变成传啥类型的值都可以

 

总结

要充分利用 FastAPI 的优势,强烈建议用 typing 的 List、Set、Tuple 来表示列表、集合、元组类型

原文:https://www.cnblogs.com/poloyy/p/15311485.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐