nex_docus/backend/app/core/database.py

42 lines
873 B
Python
Raw Normal View History

2025-12-20 11:18:59 +00:00
"""
数据库连接管理
"""
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from app.core.config import settings
# 创建异步引擎
engine = create_async_engine(
settings.DATABASE_URL,
echo=settings.DEBUG,
pool_pre_ping=True,
pool_size=10,
max_overflow=20,
)
# 创建异步会话工厂
AsyncSessionLocal = sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
2025-12-23 05:02:10 +00:00
# 别名,用于脚本中使用
async_session = AsyncSessionLocal
2025-12-20 11:18:59 +00:00
# 创建基础模型类
Base = declarative_base()
async def get_db():
"""
获取数据库会话依赖注入
"""
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()