feat(backend): 搭建 FastAPI 分层骨架 — 配置加载 / 健康检查 / SQLAlchemy+Alembic 就位

- uv 工程(Python 3.12,pyproject + uv.lock,dev: pytest/ruff)
- 分层包结构:api / application / domain / infrastructure / quant(qlib_adapter) / agent / core
- app.core.config:加载根 config.yaml + .env,sqlite 相对路径解析到项目根 data/
- SQLAlchemy Base + Session 工厂(Infrastructure 层,业务走 Repository)
- Alembic 迁移环境就位(env.py 复用应用配置,render_as_batch 兼容 SQLite)
- GET /api/health + pytest 冒烟 6 项通过 / ruff clean / uvicorn 启动验证
This commit is contained in:
Simon
2026-09-06 16:09:10 +08:00
parent 8eb3b4ac2a
commit 2a52ee5e83
32 changed files with 1443 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""基础设施层:数据库实现(SQLAlchemy / Alembic)等外部依赖的落地实现。"""
@@ -0,0 +1,5 @@
"""持久化子层:SQLAlchemy models / repositories / migrations。
约定:只在这里出现数据库实现细节;业务层不感知底层是 SQLite 还是 MySQL
(通过 DATABASE_URL 切换,见 app.core.config)。
"""
@@ -0,0 +1,64 @@
"""Alembic 迁移环境:从应用配置读取 DATABASE_URL 并连接 Base.metadata。
用法(cd backend):
uv run alembic revision --autogenerate -m "add xxx table"
uv run alembic upgrade head
"""
from __future__ import annotations
from logging.config import fileConfig
from alembic import context
from app.core.config import get_settings
from app.infrastructure.persistence.sqlalchemy.base import Base
from sqlalchemy import engine_from_config, pool
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option("sqlalchemy.url", get_settings().database_url)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""离线模式:只生成 SQL,不连接数据库。"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
render_as_batch=True, # SQLite 支持 ALTER 需要 batch 模式
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""在线模式:连接数据库执行迁移。"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
@@ -0,0 +1,27 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from __future__ import annotations
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
${imports if imports else ""}
revision: str = ${repr(up_revision)}
down_revision: str | None = ${repr(down_revision)}
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
@@ -0,0 +1 @@
"""SQLAlchemy 2.x 基础设施(当前 SQLite,未来 MySQL 同实现,仅 URL 不同)。"""
@@ -0,0 +1,12 @@
"""所有 ORM Model 的声明式基类。
新表 Model 必须继承本类;改动后通过 Alembic autogenerate 生成迁移。
"""
from __future__ import annotations
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
"""声明式 ORM 基类(SQLAlchemy 2.x 风格)。"""
@@ -0,0 +1,5 @@
"""ORM 模型目录。
新增表流程(AGENT.md §12):Model → Alembic Migration → Test。
模型统一继承 infra.persistence.sqlalchemy.base.Base。
"""
@@ -0,0 +1,5 @@
"""Repository 的 SQLAlchemy 实现。
职责:把 domain Repository Protocol 翻译成 SQLAlchemy 查询。
业务 Service 只依赖 Protocol,不 import 本目录实现(由依赖注入装配)。
"""
@@ -0,0 +1,38 @@
"""SQLAlchemy engine / Session 工厂与 FastAPI 依赖。
注意:本文件属于 Infrastructure 层,是唯一允许出现 engine 创建的地方之一。
业务 Service / Domain 禁止直接使用 Session —— 一律通过 Repository。
"""
from __future__ import annotations
from collections.abc import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from app.core.config import get_settings
_settings = get_settings()
engine = create_engine(
_settings.database_url,
echo=_settings.sqlalchemy_echo,
future=True,
)
SessionLocal = sessionmaker(
bind=engine,
autoflush=False,
expire_on_commit=False,
class_=Session,
)
def get_session() -> Generator[Session, None, None]:
"""FastAPI 依赖:每个请求一个 Session,请求结束自动关闭。
供 Repository 实现内部使用;业务层通过 Repository 间接访问。
"""
with SessionLocal() as session:
yield session