zoukankan      html  css  js  c++  java
  • FastAPI 基础学习(八) 参数附加信息 (一)

    作者:麦克煎蛋   出处:https://www.cnblogs.com/mazhiyong/ 转载请保留这段声明,谢谢!

    FastAPI支持为路径参数、请求参数添加附加信息,起到辅助说明或辅助校验的作用。

    一、请求参数附加信息

    对请求参数附加信息的支持,FastAPI通过Query模块来实现。

    1、导入Query模块

    from fastapi import Query

    2、基于Query模块声明缺省值

    可选参数声明

    q: str = Query(None)  # 等同于  q: str = None

    缺省值参数声明

    q: str = Query("query")  # 等同于  q: str = "query"

    必选参数声明

    q: str = Query(...)  # 等同于 q: str

    3、添加附加信息

    q: str = Query(None, max_length=50)  # 限制q的最大长度不超过50

    主要用于字符串参数的附加信息:

    min_length:最小长度
    max_length:最大长度
    regex:正则表达式

    主要用于自动化文档的附加信息:

    title:参数标题
    description:参数描述信息
    deprecated:表示参数即将过期

    特殊附加信息:

    alias:参数别名

    例如:

    http://127.0.0.1:8000/items/?item-query=foobaritems

    item-query并不是一个合法的Python变量名称,Python内部会对它进行转换,为了匹配到正确的参数变量我们就需要使用参数别名。

    综合示例如下:

    from fastapi import FastAPI, Query
    
    app = FastAPI()
    
    
    @app.get("/items/")
    async def read_items(
        q: str = Query(
            None,
            alias="item-query",
            title="Query string",
            description="Query string for the items to search in the database that have a good match",
            min_length=3,
            max_length=50,
            regex="^fixedquery$",
            deprecated=True
        )
    ):
        results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
        if q:
            results.update({"q": q})
        return results

    二、请求参数列表

    FastAPI基于Query模块可以支持请求参数列表,例如请求参数q可以在URL中出现多次:

    http://localhost:8000/items/?q=foo&q=bar

    对应代码实现如下:

    from typing import List
    from fastapi import FastAPI, Query
    
    app = FastAPI()
    
    
    @app.get("/items/")
    async def read_items(q: List[str] = Query(None)):
        query_items = {"q": q}
        return query_items

    返回结果内容为:

    {
      "q": [
        "foo",
        "bar"
      ]
    }

    当然这里Query也支持请求参数列表的缺省值设置。

    from typing import List
    from fastapi import FastAPI, Query
    
    app = FastAPI()
    
    
    @app.get("/items/")
    async def read_items(q: List[str] = Query(["foo", "bar"])):
        query_items = {"q": q}
        return query_items

    我们也可以用list代替List[str],但这样的话FastAPI就无法校验列表内容了。

    from fastapi import FastAPI, Query
    
    app = FastAPI()
    
    
    @app.get("/items/")
    async def read_items(q: list = Query(None)):
        query_items = {"q": q}
        return query_items
  • 相关阅读:
    OPENGLES 绘制纹理带黑圈pre-multiplying
    listview相关代码整理
    时区列表
    (迪杰斯特拉)Dijkstra算法
    全源最短路径(Floyd算法)
    go配置私有仓库 (go mod配置私有仓库)
    mingw+gcc 10.1下载
    线段树应用及概况
    清理docker常用命令
    minio设置永久访问链接
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12906795.html
Copyright © 2011-2022 走看看