37 lines
979 B
Python
37 lines
979 B
Python
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from sqlalchemy.orm import declarative_base
|
|
from .settings import get_settings
|
|
|
|
settings = get_settings()
|
|
|
|
DATABASE_URL = (
|
|
f"mysql+aiomysql://{settings.DB_USER}:{settings.DB_PASSWORD}"
|
|
f"@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}"
|
|
f"?charset={settings.DB_CHARSET}"
|
|
)
|
|
|
|
engine = create_async_engine(DATABASE_URL, echo=settings.DEBUG, future=True)
|
|
|
|
AsyncSessionLocal = async_sessionmaker(
|
|
engine, class_=AsyncSession, expire_on_commit=False
|
|
)
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
async def get_db():
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
|
|
|
|
async def init_db():
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|