zoukankan      html  css  js  c++  java
  • 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 来表示列表、集合、元组类型

  • 相关阅读:
    HiveServer2的配置使用
    hBase-thrift 实践(java)
    Building Apache Thrift on CentOS 6.5
    linux安装thrift
    Apache Thrift with Java Quickstart(thrift入门及Java实例)
    [转载]/etc/security/limits.conf解释及应用
    storm 入门原理介绍
    Storm的wordCounter计数器详解
    CentOS6.5 安装python
    HBase 协处理器统计行数
  • 原文地址:https://www.cnblogs.com/poloyy/p/15311485.html
Copyright © 2011-2022 走看看