Files
stock/backend/app/db.py
2026-08-14 17:34:26 +08:00

24 lines
763 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""async SQLAlchemy 引擎与会话。"""
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from .config import settings
class Base(DeclarativeBase):
"""所有 ORM 模型的基类。"""
# echo=False远程 PG 的空闲连接可能被中间层断开pre_ping + recycle 自动剔除死连接
engine = create_async_engine(
settings.database_url, echo=False, future=True,
pool_pre_ping=True, pool_recycle=1800,
)
async_session = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
async def get_session() -> AsyncSession:
"""FastAPI 依赖:提供一个事务会话。"""
async with async_session() as session:
yield session