36 lines
842 B
Python
36 lines
842 B
Python
"""
|
|
数据库连接管理
|
|
"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from app.core.config import settings
|
|
|
|
# 创建数据库引擎
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
echo=settings.DB_ECHO,
|
|
pool_size=settings.DB_POOL_SIZE,
|
|
max_overflow=settings.DB_MAX_OVERFLOW,
|
|
pool_timeout=settings.DB_POOL_TIMEOUT,
|
|
pool_recycle=settings.DB_POOL_RECYCLE,
|
|
pool_pre_ping=True, # 连接前测试连接是否有效
|
|
)
|
|
|
|
# 创建会话工厂
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# 创建基础模型类
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""
|
|
获取数据库会话的依赖注入函数
|
|
"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|