fastapi(六)路径参数和数值验证

你可以像在Query中定义的数据验证和metadata一样,在Path中使用。
eg:

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"),
    q: str = Query(None, alias="item-query"),
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

按需排列参数
在python中是不允许将有默认值得参数放到没有默认值的参数之前的。
但是在fastapi中,是通过参数名来识别的,类型和默认值都不重要。
在fastapi中,当查询参数q不使用Query和路径参数使用Path,并且他们可以使用任意的顺序时,可以让函数的第一个参数为*
。。。
@app.get("/items/{item_id}")
async def read_items(
*, item_id: int = Path(…, title=“The ID of the item to get”), q: str
):
。。。
数字验证
。。。
@app.get("/items/{item_id}")
async def read_items(
*, item_id: int = Path(…, title=“The ID of the item to get”, ge=1), q: str
):
。。。
ge:大于等于
gt:大于
le:小于等于
lt:小于

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值