把原本散落在 /root/zikai 的 FastAPI 服务整理到 server/ 子目录, 开启独立 git 与 venv。运行时数据(config.yaml / keys / uploads) 按 .gitignore 留在工作目录但不入仓。
42 lines
997 B
Python
42 lines
997 B
Python
"""数据库引擎、Session 与 Declarative Base。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Generator
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
|
|
|
from .config import get_settings
|
|
|
|
_settings = get_settings()
|
|
|
|
engine = create_engine(
|
|
_settings.db_url(),
|
|
pool_pre_ping=True,
|
|
pool_size=_settings.database.pool_size,
|
|
pool_recycle=_settings.database.pool_recycle,
|
|
future=True,
|
|
)
|
|
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
"""FastAPI 依赖:为每个请求产出一个 Session。"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def init_db_schema() -> None:
|
|
"""按需建表(幂等)。先导入 models 以注册映射。"""
|
|
from . import models # noqa: F401
|
|
Base.metadata.create_all(bind=engine)
|