enum枚举

  • 定义枚举的类型
class ModelName(str, Enum):
    bj = "beijing"
    nj = "nanjing"
    sh = "shanghai"
  • 定义枚举变量的参数推导
@app.get("/model/{modelName}")
async def choice(modelName:ModelName):
    if modelName == ModelName.bj:
        return "You choice is Beijjing!"
    elif modelName == ModelName.sh:
        return "Your choice is ShangHai"
    elif modelName == ModelName.nj:
        return "Your choice is Nanjing"
    else:
        return "Bad Request!"

在这种情况之下,用户只能输入指定的内容,不然的话会报错!!!

定义枚举变量的好处是为了统一进行修改,让代码可以被复用!!此外,防止进行其他的内容可以防止黑客进行注入

定义多个参数

  • FastApi可以定义多个参数
# 多个参数
@app.get("/user/{item_1}/passwd/{item_2}")
async def login(item_1: str, item_2: str):
    return {
        "Message": "Login successfully!",
        "UserName": item_1,
        "Password": item_2
    }

访问
127.0.0.1:8080/user/andytoe/passwd/123456

{
"Message":"Login successfully!",
"UserName":"andytoe",
"Password":"123456"
}

参数校验

  • 对用户输入进行校验,指定用户必须使用和不能使用什么东西
# 参数校验
@app.get("/item")
async def read_item(que:Optional[str] = Query("输出默认值", max_length=5, min_length=3)):
    if que:
        return que
    else:
        return que

上面的代码,校验了输入的长度,要求最短必须3,最长必须5。
如果输入的参数不满足这个条件,会直接报错。

如果没有输入参数,会显示默认值

  • 通过校验之后进行增加内容
# 校验合并json
@app.get("/item2")
async def read_item2(que:Optional[str] = Query("默认值",max_length=5, min_length=3)):
    result = {"item1": [{"user1": "xiaoli"}, {"user2": "xiaoming"}]}
    if que:
        # 添加进去新的数据
        result.update({"que": que})
    return result

此时访问: http://127.0.0.1:8080/item2?que=123

{"item1":
[{"user1":"xiaoli"},
{"user2":"xiaoming"}],
"que":"123"}

正则校验

  • 参数匹配正则表达式
# 匹配正则
@app.get("/regular")
async def regular(que:Optional[str] = Query("默认值",regex="^A")):
    if que:
        return que
    return que

上述代码只有当字符串从A开头的时候才能使用

其他数据类型匹配

  • 传入数组
# 匹配数组
@app.get("/list")
async def read_list(que:Optional[List[str]] = Query(None)):
    if que:
        return {"Que": que}

此时访问: http://127.0.0.1:8080/list?que=ABC&que=123

{"Que":["ABC","123"]}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐