跳转至

扩展应用

在本页中,你将为 shop 添加一个 /users 资源:先在唯一的 main.py 中手动添加,再在 layered 项目中用 fastkit addroute 添加。你将了解 FastAPI 如何用路由器(APIRouter 和 include_router)拆分应用,依赖项(Depends)如何把对象交给端点,设置如何从环境变量和 .env 中读取,以及 CORS 中间件的作用。

手动添加 /users

添加端点最快的办法是复制一个能正常工作的端点。在生成应用创建的 hello 项目中,把 Item 模型和两个条目端点复制到 main.py 的末尾,再改名为适用于用户的版本:

main.py
class User(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    email: str = Field(min_length=3, max_length=254)


class StoredUser(User):
    id: int


users: dict[int, StoredUser] = {}


@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: User) -> StoredUser:
    stored = StoredUser(id=len(users) + 1, **user.model_dump())
    users[stored.id] = stored
    return stored


@app.get("/users/{user_id}")
async def read_user(user_id: int) -> StoredUser:
    if user_id not in users:
        raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
    return users[user_id]

在 tests/test_main.py 中,把导入语句改为 from main import app, items, users,在 empty_store fixture 里的每个 items.clear() 后面加上 users.clear(),然后在文件末尾添加两个测试:

tests/test_main.py
ADA = {"name": "Ada", "email": "ada@example.com"}


def test_create_user_returns_it_with_a_new_id() -> None:
    response = client.post("/users", json=ADA)
    assert response.status_code == 201
    assert response.json() == {**ADA, "id": 1}


def test_read_user_that_does_not_exist() -> None:
    response = client.get("/users/42")
    assert response.status_code == 404
    assert response.json() == {"detail": "User not found"}
$ uv run pytest -q
............                                                             [100%]
12 passed in 0.31s

一个文件不够用的时候

fastkit addroute 可以替你添加资源,但它需要有包来存放新的模块。在 hello 项目中,它会拒绝添加资源并说明原因:

$ fastkit addroute users .
╭───────────────────────────────── Error ──────────────────────────────────╮
│ ❌ This project keeps its whole application in main.py, so there is no   │
│ package to add route modules to. Add the endpoint to main.py by hand,    │
│ next to the existing ones (copy one endpoint and its test), or create a  │
│ project at a later level with `fastkit init --level layered` (`fastkit   │
│ list-templates` lists the templates).                                    │
╰──────────────────────────────────────────────────────────────────────────╯

layered 级别把应用拆分成几个包:路由、数据访问(crud)、schema 和核心设置。fastkit 不会把项目转换成另一个级别,所以请在 hello 项目的文件夹之外创建一个新项目(当前位置还不能有 shop 文件夹)。-y 会不经询问地接受所有默认值:

$ fastkit init --level layered --name shop -y
...
$ cd shop
$ find src -name '*.py' -not -name '__init__.py' | sort
src/api/api.py
src/api/deps.py
src/api/routes/items.py
src/core/config.py
src/core/pagination.py
src/core/responses.py
src/crud/items.py
src/main.py
src/schemas/items.py

现在条目保存在 src/mocks/mock_items.json 文件中,所以重启后依然存在;而且每个端点都位于 /api/v1 之下,例如 /api/v1/items。

路由器和依赖项

APIRouter 是一组路径操作,你把它写在单独的模块中,用 @router.get(...) 代替 @app.get(...)。src/api/routes/items.py 用 APIRouter(prefix="/items", tags=["items"]) 创建了一个路由器,其前缀和标签会应用到它的每个端点上。include_router 把一个路由器的端点加入另一个路由器或应用中。src/api/api.py 汇集了所有资源的路由器:

src/api/api.py
# One APIRouter collects the routers of every module; main.py mounts it once.
# https://fastapi.tiangolo.com/tutorial/bigger-applications/
api_router = APIRouter()
api_router.include_router(items.router)
# fastkit:routes

随后,src/main.py 用 app.include_router(api_router, prefix=settings.API_V1_PREFIX) 把它挂载一次。两个文件中的 # fastkit:imports 和 # fastkit:routes 注释标记了 fastkit addroute 插入代码行的位置,请保留它们。

依赖项是 FastAPI 在你的端点之前调用的函数,端点会收到它的返回值。你用 Depends(...) 声明依赖项,再定义一个 Annotated 别名,就能让每个端点复用它:

src/api/deps.py
def get_item_store() -> ItemStore:
    """Return the item store (tests override this dependency)."""
    return item_store
# ...
ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)]

每个条目端点都声明了 store: ItemStoreDep,例如 def get_item(item_id: int, store: ItemStoreDep) -> ItemRead。由于没有哪个端点自己创建存储,测试可以用自己的存储替换 get_item_store(具体做法见测试应用)。

设置和 CORS

设置是因机器而异的值,例如密钥或允许的来源。pydantic-settings 的 BaseSettings 类会从同名的环境变量或 .env 文件中读取每个字段,都没有时则使用默认值:

src/core/config.py
class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_ignore_empty=True,
        extra="ignore",
    )

fastkit 生成 .env 时写入了唯一的 SECRET_KEY。Git 会忽略 .env;.env.example 则为后来的人列出所有设置。其中一项是 BACKEND_CORS_ORIGINS。当来自另一个来源(协议、主机和端口)的网页调用这个 API 时,浏览器会读取 API 返回的 CORS 头部,再决定该网页能否读取响应。CORS 中间件会为你列出的来源发送这些头部,例如在 .env 中设置 BACKEND_CORS_ORIGINS=http://localhost:3000;只有当这个列表不为空时,src/main.py 才会安装该中间件。CORS 不是认证:它无法阻止 curl 或其他服务器之类的客户端调用这个 API。

用 fastkit 添加 users

--dry-run 会列出 fastkit addroute 将要写入的内容;--diff 还会打印每一处改动:

$ fastkit addroute users . --dry-run
...
Files to create (4):
  + src/api/routes/users.py
  + src/crud/users.py
  + src/schemas/users.py
  + tests/test_users.py
Files to modify (2):
  ~ src/api/deps.py
  ~ src/api/api.py
...

去掉 --dry-run 再运行一次,并确认执行。新资源在 /api/v1/users 下提供分页列表、创建(201)、获取、替换(PUT)、更新(PATCH)和删除(204),并为每一项附带测试。它的 schema 最初包含 name 和 description 字段;要使用你自己的字段,请编辑 src/schemas/users.py。src/api/api.py 会在两个标记下方加入该路由器的导入语句和 include_router 行,src/api/deps.py 则会加入新的依赖项别名,供 src/api/routes/users.py 导入:

src/api/deps.py
from src.crud.users import UserRepository, get_user_repository
# ...
UserRepositoryDep = Annotated[UserRepository, Depends(get_user_repository)]

现在 uv run pytest -q 会报告 91 passed:其中 74 个是项目自带的测试,17 个是 tests/test_users.py 中新增的测试。

在 hello 和 layered 之间还有 single-file 级别:整个应用放在一个 src/main.py 中,并配有设置和测试。在这个级别下第一次使用 fastkit addroute 时,它会在 src/main.py 周围添加 api、crud、schemas 和 core 这几个包。

FastAPI 文档

下一步

测试应用阅读 layered 项目的测试,并编写一个新的测试。