跳转至

迁移到领域结构和数据库

在本页中,你将把 shop 迁移到 domain 级别,在这个级别中条目保存在 SQL 数据库里。你将了解 FastAPI 如何通过 SQLAlchemy 使用异步 SQL 数据库,使用 yield 的依赖项如何为每个请求提供数据库会话并在之后完成清理,什么是 Lifespan 事件,以及领域包如何把一个资源拆分成路由器、服务和仓储。你还会用到 fastkit 的 --database 选项、Alembic 迁移选项和生成的 README 中的“Selected features”部分,并在领域项目中使用 fastkit addroute。

下一个级别的新项目

fastkit 不会把项目转换成另一个级别。你需要创建一个新项目,再把自己的代码移进去。由于新项目同样叫 shop,请在 layered 级别 shop 项目以外的文件夹中操作:

$ fastkit init --level domain --name shop --database SQLite --feature migrations=Alembic --no-venv -y
...
│ Database        │ SQLite                                                     │
│ Features        │ Testing: Coverage; Migrations: Alembic                     │
...

SQLite 把整个数据库保存在一个文件中,不需要服务器,因此适合开发使用。Alembic 选项会添加数据库迁移;Testing: Coverage 是 hello 之后每个级别都有的、带 pytest-cov 的测试配置。README.md 在“Selected features”下为它们各写了一节,说明它的作用、它添加的文件以及它读取的设置。新生成的文件如下:

$ cd shop
$ find src alembic -type f -not -name '__init__.py' | sort
alembic/env.py
alembic/script.py.mako
alembic/versions/182fb3ba8f64_initial.py
...
src/app/core/database.py
...
src/app/domains/items/models.py
src/app/domains/items/repository.py
src/app/domains/items/router.py
src/app/domains/items/schemas.py
src/app/domains/items/service.py
src/app/features/readiness.py
src/app/main.py

一个领域:items

领域包把与一个资源有关的所有内容放在同一个文件夹中。在 src/app/domains/items/ 中,router.py 处理 HTTP,service.py 存放业务规则,repository.py 执行 SQL,models.py 描述数据表,schemas.py 描述 JSON。路由器通过依赖项 get_item_service(session: SessionDep) 获取服务,这个依赖项把请求的数据库会话包装进 ItemRepository,再把该仓储包装进 ItemService。条目不存在时,服务会抛出自己的错误,路由器再把它转换成 404。处理函数都是 async def,并 await 数据库:某个请求等待数据库时,服务器可以处理其他请求。仓储是唯一包含 SQL 的地方:

src/app/domains/items/repository.py
    async def add(self, name: str, price: float, in_stock: bool = True) -> Item:
        """Store a new item and commit; the database hands out its id."""
        item = Item(name=name, price=price, in_stock=in_stock)
        self.session.add(item)
        await self.session.commit()
        await self.session.refresh(item)
        return item

数据库会话

SQLAlchemy 的引擎维护一个数据库连接池。会话为一个工作单元借用一个连接。src/app/core/database.py 创建引擎和会话,并为每个请求提供一个会话:

src/app/core/database.py
# A dependency with `yield` gives the endpoint a session and closes it afterwards.
# https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
async def get_db() -> AsyncIterator[AsyncSession]:
    """Yield one session per request and roll it back if the request fails."""
    async with SessionLocal() as session:
        try:
            yield session
        except Exception:
            await session.rollback()
            raise


#: ``session: SessionDep`` in an endpoint or service dependency signature.
SessionDep = Annotated[AsyncSession, Depends(get_db)]


# A lifespan runs its code after `yield` once, when the application shuts down.
# https://fastapi.tiangolo.com/advanced/events/
@asynccontextmanager
async def engine_lifespan(_app: FastAPI) -> AsyncIterator[None]:
    """Dispose of the connection pool when the application shuts down."""
    try:
        yield
    finally:
        await engine.dispose()

对于使用 yield 的依赖项,FastAPI 会先运行到 yield 为止,把 yield 出的值传给端点,在响应之后再运行剩下的部分。在这里,剩下的部分会在有异常经过时回滚会话中尚未提交的工作,而 async with 总会关闭会话。它不会撤销整个请求:每个仓储方法都会提交自己的改动(await self.session.commit()),已经提交的内容会保持提交状态。lifespan 以同样的方式作用于整个应用:yield 之前的代码在启动时运行,之后的代码在关闭时运行。src/app/main.py 用 app.include_router(database_lifespan) 添加这个 lifespan。数据库的 URL 来自设置 DATABASE_URL,默认值为 sqlite+aiosqlite:///./app.db。

创建数据表

Alembic 通过 alembic/versions/ 中的迁移脚本创建和修改数据表。第一个脚本会创建 items 表:

$ uv sync -q
$ uv run alembic upgrade head
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 182fb3ba8f64, initial revision

以后修改模型时,README 的 Alembic 一节说明了如何记录这次改动:alembic revision --autogenerate -m "add orders"。自动生成的修订版本只是草稿:在它作用于真实数据之前,请先阅读并测试它,因为 Alembic 会猜错某些改动(例如重命名的列会被当成删除一列再新增一列)。

条目在重启后依然存在

用 uv run uvicorn src.app.main:app 启动服务器。在第二个终端中创建一个条目:

$ curl -s -X POST http://127.0.0.1:8000/api/v1/items -H "Content-Type: application/json" -d '{"name": "Lamp", "price": 25.5}'
{"id":1,"name":"Lamp","price":25.5,"in_stock":true}

按 Ctrl+C 停止服务器,再重新启动,然后列出条目。那盏台灯还在,而且因为数据库有响应,/ready 返回 ok:

$ curl -s http://127.0.0.1:8000/api/v1/items
{"items":[{"id":1,"name":"Lamp","price":25.5,"in_stock":true}],"total":1,"limit":20,"offset":0}
$ curl -s http://127.0.0.1:8000/ready
{"status":"ok"}

把 users 迁移过来

fastkit addroute 在领域项目中同样可用,它会创建一个领域包:

$ fastkit addroute users .
...
Files to create (7):
  + src/app/domains/users/__init__.py
...
  + tests/test_users.py
Files to modify (1):
  ~ src/app/api/router.py
Note: users keeps its records in memory (src/app/domains/users/repository.py); src/app/domains/items/ shows the SQL-backed version (model, repository, service and router); an Alembic revision in alembic/versions/ creates its table.

Do you want to add route 'users' to the current project? [Y/n]: y
...

要为 users 建一张数据表,请参照提示中提到的 items 文件。你在测试应用中编写的测试也可以搬过来,只是要换成新的导入语句,因为这里的端点是从 get_user_service 获取 UserService 的。修改下面这几行即可,文件的其余部分保持不变,91 个测试全部通过:

tests/test_users_override.py
from src.app.domains.users.repository import UserRepository
from src.app.domains.users.router import get_user_service
from src.app.domains.users.service import UserService
from src.app.main import app
# ...
    app.dependency_overrides[get_user_service] = lambda: UserService(repository)

切换到 PostgreSQL

PostgreSQL 是数据库服务器,所以你需要运行一个,例如在 Docker 中运行。然后安装它的异步驱动 asyncpg,并把 DATABASE_URL 指向该服务器:

$ docker run -d --name shop-db -e POSTGRES_USER=shop -e POSTGRES_PASSWORD=shop -e POSTGRES_DB=shop -p 5432:5432 postgres:16-alpine
0acce6b1c7b75671fb3d42ef3bd279825c9a256825131db2a0bc70b0206b3ba0
$ uv add asyncpg
...
 + asyncpg==0.32.0

在 .env 中添加一行 DATABASE_URL=postgresql+asyncpg://shop:shop@localhost:5432/shop。这个 URL 的格式是 postgresql+asyncpg://USER:PASSWORD@HOST:PORT/DATABASE。alembic upgrade head 会在这个新的空数据库中创建数据表;SQLite 文件 app.db 中的数据行不会被复制过来。创建数据表,重新启动服务器,然后创建一个条目:

$ uv run alembic upgrade head
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 182fb3ba8f64, initial revision
$ curl -s -X POST http://127.0.0.1:8000/api/v1/items -H "Content-Type: application/json" -d '{"name": "Desk", "price": 120}'
{"id":1,"name":"Desk","price":120.0,"in_stock":true}
$ docker exec shop-db psql -U shop -c "SELECT * FROM items;"
 id | name | price | in_stock
----+------+-------+----------
  1 | Desk |   120 | t
(1 row)

Python 代码一行都没有改。测试仍然在内存中的 SQLite 数据库上运行(项目根目录下的 conftest.py 会在导入应用之前完成这项设置),因此 uv run pytest 不需要服务器。用完之后,docker rm -f -v shop-db 会删除该容器及其数据。

FastAPI 文档

下一步

部署到生产环境在 production 级别创建 shop,加入登录、结构化日志和容器。