aidress/app/database/__init__.py
2025-03-21 17:06:54 +08:00

28 lines
773 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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()