25 lines
618 B
Python
25 lines
618 B
Python
"""MySQL 异步连接(SQLAlchemy 2.0 async)"""
|
||
from collections.abc import AsyncGenerator
|
||
|
||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||
|
||
from app.config import settings
|
||
|
||
engine = create_async_engine(
|
||
settings.database_url,
|
||
pool_size=20,
|
||
max_overflow=10,
|
||
pool_recycle=3600,
|
||
pool_pre_ping=True,
|
||
echo=False,
|
||
)
|
||
|
||
SessionFactory = async_sessionmaker(
|
||
engine, class_=AsyncSession, expire_on_commit=False, autoflush=False
|
||
)
|
||
|
||
|
||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||
async with SessionFactory() as session:
|
||
yield session
|