除了可以为Query查询参数声明校验和元数据,还可以为Path路径参数声明相同类型的校验和元数据。

声明元数据

可以声明与Query相同的所有参数。

例如:为路径参数item_id声明title元数据的值时,可以输入:

from typing import Optional
from fastapi import FastAPI. Path, Query

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(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:
        result.update({"q": q})
    return results

因为路径参数必须是路径的一部分,所以路径参数总是必选的,因此,声明路径参数时要使用...,把它标记为必选参数。不过,就算使用None声明路径参数,或设置其他默认值也不会有任何影响,路径参数依然是必选参数。

按需排序参数

假设要把查询参数q声明为必选的str类型。而且,因为不用为该参数声明任何其他内容,因此无需使用Query。但仍然使用Path声明路径参数item_id,如果把有默认值的参数置于无默认值的参数前,python会报错,但可以重新排序,把无默认值的查询参数q放到最前面。

from fastapi import FastAPI, Path

app = FastAPI()

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

 

按需排序参数的技巧

如果不想使用Query声明没有默认值的查询参数q,但同时还要使用Path声明路径参数item_id,并使用不同的排序方式,可以使用python的特殊语法。把*作为函数的第一个参数,python不对*执行任何操作,但会把*之后的参数都当做关键字参数。

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

 

数值校验:大于等于

使用QueryPath时,既可以声明字符串约束,也可以声明数值约束。此处,添加ge=1后,item_id就必须就必须是大于等于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

 

数值校验:大于、小于等于

  • gt:大于
  • le:小于等于
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值,此处,重要的是声明gt,而不仅是ge,例如,值必须大于0,即使该值小于1,因此,0.5是有效的,但0.00是无效的。

from fastapi import FastAPI, Path, Query

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(*, 
                    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:大于
  • ge:大于等于
  • lt:小于
  • le:小于等于
posted on 2022-05-05 11:40  司徒轩宇  阅读(77)  评论(0编辑  收藏  举报