admin管理员组

文章数量:1487745

FastAPI后台开发基础(2):路径参数

路径参数的类型 int / str

示例代码

代码语言:python代码运行次数:0运行复制
from __future__ import annotations

import uvicorn
from fastapi import FastAPI

app = FastAPI()

# 路径中的参数区分类型,比如 str 和 int,在打印时一个会带引号,一个不带引号
# curl -X 'GET' 'http://127.0.0.1:8000/str/123' -H 'accept: application/json'
# {
#   "message": [
#     "123"
#   ]
# }
@app.get("/str/{some_str}")
async def hello_some_str(some_str: str):
    return {"message": {some_str}}

# 正常的 int 参数
# curl -X 'GET' 'http://127.0.0.1:8000/int/123' -H 'accept: application/json'
# {
#   "message": [
#     123
#   ]
# }
# 传入 abc 时会报错,因为 abc 并不是 int 类型
# curl -X 'GET' 'http://127.0.0.1:8000/int/abc' -H 'accept: application/json'
# {
#     "detail": [
#         {
#             "type": "int_parsing",
#             "loc": [
#                 "path",
#                 "some_int"
#             ],
#             "msg": "Input should be a valid integer, unable to parse string as an integer",
#             "input": "abc"
#         }
#     ]
# }
@app.get("/int/{some_int}")
async def hello_some_int(some_int: int):
    return {"message": {some_int}}

访问 str

代码语言:python代码运行次数:0运行复制
curl -X 'GET' 'http://127.0.0.1:18081/str/123' -H 'accept: application/json'
{"message":["123"]}
字符串参数

访问 int

代码语言:python代码运行次数:0运行复制
curl -X 'GET' 'http://127.0.0.1:18081/int/123' -H 'accept: application/json'
{"message":[123]}
整型参数

参数类型校验

代码语言:python代码运行次数:0运行复制
curl -X 'GET' 'http://127.0.0.1:18081/int/abc' -H 'accept: application/json'
{"detail":[{"type":"int_parsing","loc":["path","some_int"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}
错误参数校验效果

路径优先匹配

示例代码

代码语言:python代码运行次数:0运行复制
from __future__ import annotations

import uvicorn
from fastapi import FastAPI

app = FastAPI()

# 总是返回 first,因为这个最先匹配
@app.get('/first')
async def first():
    return {'message': 'first'}


@app.get('/first')
async def second():
    return {'message': 'second'}

当定义了两个 first 时,总是返回第一个路由绑定的函数。

访问 /first 路径

总是返回第一个匹配的路由

路径参数为枚举值

示例代码

代码语言:python代码运行次数:0运行复制
from __future__ import annotations

from enum import Enum

import uvicorn
from fastapi import FastAPI

app = FastAPI()


class ParamEnum(str, Enum):
    """
    同时继承自 str 和 Enum
    这意味着枚举的每个成员都是 str 类型的实例
    这样做的好处是你可以直接将枚举成员当作字符串使用
    享受字符串的所有方法和属性
    同时保持枚举的唯一性和不可变性
    """
    a = "aaa"
    b = "bbb"
    c = "ccc"


@app.get("/{param}")
async def async_root(param: ParamEnum = ParamEnum.a):
    if param == ParamEnum.a:
        return {"message": ParamEnum.a.capitalize()}
    elif param == ParamEnum.b:
        return {'message': ParamEnum.b.lower()}
    elif param == ParamEnum.c:
        return {'message': ParamEnum.c.upper()}


if __name__ == '__main__':
    uvicorn.run(app, host = '127.0.0.1', port = 18081)

查看文档

打开http://127.0.0.1:18081/docs#/default/async_root__param__get:

路径参数为枚举值

使用枚举值作为路径参数

枚举值作为路径参数
使用非枚举值作为路径参数

路径参数使用正则匹配

示例代码

代码语言:python代码运行次数:0运行复制
from __future__ import annotations

import uvicorn
from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/items/{id_num}")
async def read_item(id_num: str = Path(...,
                                       description = "using the regex parameter to deliver the regular rules",
                                       regex = r"^[a-z0-9]{1,10}$")):
    """
    DeprecationWarning: `regex` has been deprecated, please use `pattern` instead
    """
    return {"id_num": id_num.upper()}


@app.get("/items_2/{id_num_2}")
async def read_item_2(id_num_2: str = Path(...,
                                           description = "using the pattern parameter to deliver the regular rules",
                                           pattern = r"^[A-Z0-9]{1,10}$")):
    return {"id_num_2": id_num_2.lower()}


if __name__ == '__main__':
    uvicorn.run(app, host = '127.0.0.1', port = 18081)

查看文档

正则匹配参数的文档描述

使用正确的参数

正确匹配正则的参数

使用不正确的参数

无法匹配正则规则的参数

带有/字符的路径参数

示例代码

代码语言:python代码运行次数:0运行复制
from __future__ import annotations

import uvicorn
from fastapi import FastAPI, Path

app = FastAPI()


@app.get("/test/{str_value}")
async def async_root(str_value: str):
    """
    curl -X 'GET' 'http://127.0.0.1:18081/test/%2Fabc' -H 'accept: application/json'
    {"detail":"Not Found"}
    """
    return {"message": str_value}

@app.get("/test_2/{str_value:path}")
async def async_root_2(str_value: str):
    """
    curl -X 'GET' 'http://127.0.0.1:18081/test_2/%2Fabc' -H 'accept: application/json'
    {"message":"/abc"}
    """
    return {"message": str_value}

if __name__ == '__main__':
    uvicorn.run(app, host = '127.0.0.1', port = 18081)
明确允许参数为路径

访问效果

参数带有/ 时访问失败
参数带有 / 时访问成功

本文标签: FastAPI后台开发基础(2)路径参数