05 FastApi的路径参数和数值校验

2022-05-20  本文已影响0人  萧酃

FastApi允许用户添加额外声明和校验

@app.get("/extra_para")
async def extra_paramaters(normal_int:int=None,
                           normal_str:str=None,
                           union :Union[int,str] = None):
    """

    :param normal_int: 类型必须为int
    :param normal_str: 类型必须为int
    :param union: 类型必须为int或者str
    :return:
    """
    return {"normal_int":normal_int,
            "normal_str":normal_str,
            "union":union}

1> 额外的校验——导入Query

from fastapi import Query
@app.get("/extra_param/")
async def Extra_Parameters(union :Union[int,str]=Query(
                               default=None,
                               max_length=50,
                               min_length=5
                           )):
    """
    :param union: 此处添加的额外的校验,默认是None
                  可为int类型,可为str类型,为str类型时 字符长度5<=len<=50
    :return:
    """
    return {"union":union}

2> Query 用与查询参数校验

def Query(  # noqa: N802
    default: Any,
    # 默认值 当default = ..., 表明该参数为必须
    *,
    alias: Optional[str] = None,
    # 别名
    title: Optional[str] = None,
    description: Optional[str] = None,
    gt: Optional[float] = None,
    ge: Optional[float] = None,
    lt: Optional[float] = None,
    le: Optional[float] = None,
    min_length: Optional[int] = None,
    max_length: Optional[int] = None,
    regex: Optional[str] = None,
    # 正则表达式
    example: Any = Undefined,
    examples: Optional[Dict[str, Any]] = None,
    deprecated: Optional[bool] = None,
    **extra: Any,
) -> Any:

3> Path 用于路径参数的校验, 用法与Query基本相同

def Path(  # noqa: N802
    default: Any,
    *,
    alias: Optional[str] = None,
    title: Optional[str] = None,
    description: Optional[str] = None,
    gt: Optional[float] = None,
    ge: Optional[float] = None,
    lt: Optional[float] = None,
    le: Optional[float] = None,
    min_length: Optional[int] = None,
    max_length: Optional[int] = None,
    regex: Optional[str] = None,
    example: Any = Undefined,
    examples: Optional[Dict[str, Any]] = None,
    deprecated: Optional[bool] = None,
    **extra: Any,
) -> Any:
上一篇下一篇

猜你喜欢

热点阅读