Files
diary-news/backend/app/database.py

53 lines
1.2 KiB
Python
Raw Normal View History

"""异步 SQLAlchemy 数据库连接。"""
from __future__ import annotations
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase
from app.config import settings
class Base(DeclarativeBase):
"""所有 ORM 模型的基类。"""
engine = create_async_engine(
settings.database_url,
echo=False,
pool_size=5,
max_overflow=10,
pool_pre_ping=True,
pool_recycle=1800,
)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autoflush=False,
)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
"""FastAPI 依赖:请求级 session。"""
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def init_db() -> None:
"""开发期用,生产请用 alembic。"""
# import models to register them
from app.models import article, source, user # noqa: F401
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)