| 123456789101112131415161718192021222324 |
- from sqlalchemy import create_engine
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm import sessionmaker
- from app.config import settings
- # 配置连接池参数以避免连接丢失问题
- engine = create_engine(
- settings.DATABASE_URL,
- pool_pre_ping=True, # 连接前测试连接是否有效
- pool_recycle=300, # 每5分钟重新创建连接
- pool_size=10, # 连接池大小
- max_overflow=20, # 最大溢出连接数
- echo=False # 关闭SQL日志(生产环境)
- )
- SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
- Base = declarative_base()
- def get_db():
- db = SessionLocal()
- try:
- yield db
- finally:
- db.close()
|