Files
qlib/backend/app/infrastructure/persistence/sqlalchemy/session.py
T
Simon 2a52ee5e83 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 启动验证
2026-09-06 16:09:10 +08:00

39 lines
993 B
Python

"""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