【FastAPI基础】6、对路径参数进行数值校验

22 篇文章 23 订阅

引言:

最近工作中有机会接触FastAPI这个框架,所以就把官方文档看了一遍,对框架的各个特性及使用方法做了总结,会逐步的发出来,希望对您有用。

如果您之前接触过python的其他框架,看起来会非常简单和顺畅,其实就是很简单。

【上一篇】:【FastAPI基础】5、查询参数和字符串校验
【下一篇】:【FastAPI基础】7、请求体-多个参数
【FastAPI搭建好的产品框架源码,直接上手】:【FastAPI搭建好的产品架构】,直接上手

首先,从 fastapi 导入 Path:

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

1、数值校验:大于等于

  • 使用 Query 和 Path(以及你将在后面看到的其他类)可以声明字符串约束,但也可以声明数值约束。
  • 像下面这样,添加 ge=1 后,item_id 将必须是一个大于(greater than)或等于(equal)1的整数。
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", ge=1), q: str
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

2、数值校验:大于和小于等于
同样的规则适用于:

  • gt:大于(greater 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

3、数值校验:浮点数、大于和小于

  • 数值校验同样适用于 float 值。
  • 能够声明 gt 而不仅仅是 ge 在这个前提下变得重要起来。例如,你可以要求一个值必须大于 0,即使它小于 1。
  • 因此,0.5 将是有效值。但是 0.0或 0 不是。
  • 对于 lt 也是一样的。
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

总结:
声明数值校验类型,就平常用的那几个:

  • gt:大于(greater than)
  • ge:大于等于(greater than or equal)
  • lt:小于(less than)
  • le:小于等于(less than or equal)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈建华呦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值