""" 数据库配置和连接管理 """ import os from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy.orm import declarative_base from dotenv import load_dotenv load_dotenv() DATABASE_URL = os.getenv( "DATABASE_URL", "postgresql+asyncpg://postgres:postgres123@localhost:5432/flexible_test_platform" ) engine = create_async_engine( DATABASE_URL, echo=True, # 开发环境打印 SQL pool_pre_ping=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 finally: await session.close()