database.py 740 B

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