| 12345678910111213141516171819202122232425262728 |
- from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
- from sqlalchemy.orm import declarative_base
- from app.core.config import settings
- # 创建异步引擎
- print(settings.DATABASE_URL)
- engine = create_async_engine(
- settings.DATABASE_URL,
- echo=False,
- pool_size=20,
- max_overflow=10,
- pool_recycle=3600, # 自动回收连接,防止 MySQL gone away
- pool_pre_ping=True,
- )
- # 会话工厂
- AsyncSessionLocal = async_sessionmaker(
- bind=engine,
- class_=AsyncSession,
- expire_on_commit=False
- )
- Base = declarative_base()
- async def get_db():
- """依赖注入用的 DB Session"""
- async with AsyncSessionLocal() as session:
- yield session
|