fastApi笔记05-路径参数和数值校验

本文介绍了如何在FastAPI中使用`Path`和`Query`声明参数,包括路径参数的必需性、参数排序、使用`Annotated`进行类型和约束定义,以及数值校验的使用方法。
摘要由CSDN通过智能技术生成

使用Path可以对路径参数声明与Query相同类型的校验和元数据

from typing import Annotated

from fastapi import FastAPI, Path, Query

app = FastAPI()


@app.get("/items/{item_id}")
async def read_items(
    item_id: Annotated[int, Path(title="The ID of the item to get")],
    q: Annotated[str | None, Query(alias="item-query")] = None,
):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

路径参数一定是必需的,因为它必须是路径的一部分。

按需对参数进行排序

当声明一个必需的str类型查询参数时,并且不需要任何校验,所以不需要使用Query。但是仍需要使用Path来声明路径参数时,如果你将带有「默认值」的参数放在没有「默认值」的参数之前,Python 将会报错(这是python函数语法要求的,FastApi是不在乎顺序的)

 可以通过传递*来作为第一个函数,这样python就知道之后的所有参数都应作为关键字参数(键值对),也被称为 kwargs,来调用。即使它们没有默认值

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

数值校验

 使用Query或Path都可以声明字符串约束,也可以声明数值约束

  • gt:大于(greater than)
  • ge:大于等于(greater than or equal)
  • lt:小于(less than)
  • le:小于等于(less than or equal)
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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值