Files
FlexibleTestPlatform/backend/app/database.py
2026-02-05 16:25:52 +08:00

39 lines
806 B
Python

"""
数据库配置和连接管理
"""
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()