随笔 - 214  文章 - 12  评论 - 40  阅读 - 38万

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   麦克煎蛋  阅读(1288)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示