fastapi_library/app/core/database.py
2025-06-05 18:09:51 +08:00

32 lines
1.2 KiB
Python

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from app.core.config import settings
engine = create_async_engine(
f"mysql+aiomysql://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}",
pool_size=settings.DB_POOL_SIZE, # 连接池常驻连接数
max_overflow=settings.DB_MAX_OVERFLOW, # 池最大溢出连接数
pool_timeout=settings.DB_POOL_TIMEOUT, # 获取连接超时时间(秒)
pool_recycle=settings.DB_POOL_RECYCLE, # 连接回收间隔(秒)
echo=False # 关闭SQL日志输出
)
# expire_on_commit=False 禁用提交后过期对象 --> 提交后原对象仍然可以使用.
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# ORM模型基类
Base = declarative_base()
# 获取数据库会话
async def get_db():
async with async_session() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()