FastAPI 基础学习(九) 参数附加信息 (二)

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

 

三、路径参数附加信息

对路径参数附加信息的支持,FastAPI通过Path模块来实现。

1、导入Path模块

from fastapi import Path

2、添加附加信息

所有适用于请求参数的附加信息同样适用于路径参数,如title等。

item_id: int = Path(..., title="The ID of the item to get")  

注意,路径参数在URL里是必选的,因此Path的第一个参数是...,即使你传递了None或其他缺省值,也不会影响参数的必选性。

 

代码示例:

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: int = Path(..., title="The ID of the item to get")
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

四、路径参数、请求参数顺序问题

1、不带缺省值的参数应放在前面

如果把带有缺省值的参数放在了不带缺省值的参数前面,Python会发出运行警告。

因此在实际使用时,我们应当把不带缺省值的参数放在前面,无论这个参数是路径参数还是请求参数。

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    q: str, item_id: int = Path(..., title="The ID of the item to get")
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

FastAPI根据参数名称、类型以及声明方法(如Query、Path等等)来识别具体参数意义,并不关心参数顺序。

2、参数排序的技巧

通过传递 * 作为第一个参数,就解决了上面的参数顺序问题。

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *, item_id: int = Path(..., title="The ID of the item to get"), q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

Python并不会对 * 做任何操作。但通过识别 *,Python知道后面所有的参数都是关键字参数(键值对),通常也叫kwargs,无论参数是否有默认值。

五、数字类型参数的校验

借助Query、Path等模块你可以声明对字符串类型参数的校验,同样的,也可以实现对数字类型参数的校验功能。

附加参数信息说明:

gt: 大于(greater than)
ge: 大于或等于(greater than or equal)
lt: 小于(less than)
le: 小于或等于( less than or equal)

具体示例如下:

from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", gt=0, le=1000),
    q: str,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

数字校验同样也适用于float类型的参数。

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    *,
    item_id: int = Path(..., title="The ID of the item to get", ge=0, le=1000),
    q: str,
    size: float = Query(..., gt=0, lt=10.5)
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

 

posted on 2020-05-18 21:20  麦克煎蛋  阅读(1251)  评论(0编辑  收藏  举报