22 lines
641 B
Python
22 lines
641 B
Python
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()
|
|
|
|
# pool_pre_ping避免调度器长时间空闲后拿到失效的MySQL连接。
|
|
engine = create_engine(settings.database_url, pool_pre_ping=True, future=True)
|
|
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
# FastAPI依赖负责在请求结束后关闭数据库会话。
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|