39 lines
874 B
Python
39 lines
874 B
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import QueuePool
|
|
|
|
from app.config.settings import settings
|
|
|
|
# 创建数据库引擎
|
|
engine = create_engine(
|
|
settings.DATABASE_URL,
|
|
poolclass=QueuePool,
|
|
pool_pre_ping=True,
|
|
pool_size=10,
|
|
max_overflow=20,
|
|
pool_recycle=3600, # 连接回收时间
|
|
pool_timeout=30, # 连接超时时间
|
|
echo=False # 关闭SQL日志
|
|
)
|
|
|
|
# 创建会话工厂
|
|
SessionLocal = sessionmaker(
|
|
autocommit=False,
|
|
autoflush=False,
|
|
bind=engine,
|
|
expire_on_commit=False # 提交后不自动过期对象
|
|
)
|
|
|
|
# 创建基类
|
|
Base = declarative_base()
|
|
|
|
|
|
def get_db():
|
|
"""获取数据库会话的依赖函数"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|