[backend] feat: 添加项目基础配置

This commit is contained in:
xsl
2026-01-26 08:09:35 +08:00
parent e4b59c5ee4
commit 827549fa0d
7 changed files with 86 additions and 0 deletions
+36
View File
@@ -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)