42 lines
873 B
Python
42 lines
873 B
Python
"""
|
|
数据库连接管理
|
|
"""
|
|
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,
|
|
)
|
|
|
|
# 别名,用于脚本中使用
|
|
async_session = AsyncSessionLocal
|
|
|
|
# 创建基础模型类
|
|
Base = declarative_base()
|
|
|
|
|
|
async def get_db():
|
|
"""
|
|
获取数据库会话(依赖注入)
|
|
"""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
finally:
|
|
await session.close()
|