28 lines
773 B
Python
28 lines
773 B
Python
from sqlalchemy import create_engine
|
||
from sqlalchemy.ext.declarative import declarative_base
|
||
from sqlalchemy.orm import sessionmaker
|
||
from app.utils.config import get_settings
|
||
|
||
settings = get_settings()
|
||
|
||
# 创建数据库引擎
|
||
engine = create_engine(
|
||
settings.database_url,
|
||
pool_pre_ping=True, # 自动检测断开的连接并重新连接
|
||
pool_recycle=3600, # 每小时回收连接
|
||
echo=settings.debug, # 在调试模式下打印SQL语句
|
||
)
|
||
|
||
# 创建会话工厂
|
||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||
|
||
# 创建Base类,所有模型都将继承这个类
|
||
Base = declarative_base()
|
||
|
||
# 获取数据库会话的依赖函数
|
||
def get_db():
|
||
db = SessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close() |