[backend] feat: 添加项目基础配置
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user