Path 参数

947 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

上一章我们知道了,如何返回一个列表,下面我们来返回一个用户的详情信息

from fastapi import FastAPI, HTTPException

app = FastAPI()
users = [
    {"name": "Trevor", "age": 30, "id": 1},
    {"name": "Foo", "age": 20, "id": 2},
    {"name": "Foo3", "age": 20, "id": 3},
    {"name": "Foo4", "age": 20, "id": 4},
    {"name": "Foo5", "age": 20, "id": 5},
    {"name": "Foo6", "age": 20, "id": 6},
    {"name": "Foo7", "age": 20, "id": 7},
    {"name": "Foo8", "age": 20, "id": 8},
    {"name": "Foo9", "age": 20, "id": 9},
    {"name": "Foo10", "age": 20, "id": 10},
]


@app.get('/users/{id}')
def user_detail(id: int):
    filterd = list(filter(lambda i: i["id"] == id, users))
    if filterd:
        return filterd[0]
    else:
        raise HTTPException(404)

运行一下看到以下效果

Screen Shot 2021-09-18 at 8.46.54 PM

我们给请求参数中path增加了变量,你可以像 Query 参数一样指定参数类型,FastAPI 会自动进行校验

@app.get('/users/{id}')
def user_detail(id: int):

预定义变量 - 枚举类型

我们预置了2种类型的用户,adminnormal,如果不想硬编码在代码中,这就需要用到枚举变量。


class UserType(str, Enum):
    ADMIN = "admin"
    NORMAL = "normal"

@app.get('/users/{type}')
def users(type: Optional[UserType] = None):
    if not type:
        return users
    return list(filter(lambda x: x['user_type'] == type, users))

Screen Shot 2021-09-18 at 9.10.35 PM

@app.get('/users/{type}')@app.get('/users/{id}') 不能同时出现在代码中,因为两个接口的匹配逻辑一样,FastAPI 是按照顺序进行匹配的,只会配到前面一个。

文件路径支持

如果请求路径中出现了文件路径怎么办?例如想从一个路径中获取一个文件,但是想使用path 可以如下定义:(虽然支持,但是不推荐使用,容易歧义)

from fastapi import FastAPI

app = FastAPI()


@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    return {"file_path": file_path}	

这样files/ 后面的参数就会被认为是 file path。例如:/files/home/johndoe/myfile.txt,被认为是获取 home/johndoe/myfile.txt 这个文件

本文中的代码可以到这里下载