2025-04-30 04:39:36 +08:00

53 lines
2.2 KiB
Python

# File: backend/app/api/v1/endpoints/sessions.py (Update with DB session dependency)
# Description: 会话管理的 API 路由 (使用数据库会话)
from fastapi import APIRouter, HTTPException, Depends, status
from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.database import get_db_session
from app.models.pydantic_models import SessionRead, SessionCreateRequest, SessionCreateResponse
from app.services.session_service import SessionService # Import the class
router = APIRouter()
session_service = SessionService() # Create instance
@router.post("/", response_model=SessionCreateResponse, status_code=status.HTTP_201_CREATED)
async def create_new_session(
session_data: SessionCreateRequest,
db: AsyncSession = Depends(get_db_session) # Inject DB session
):
try:
return await session_service.create_session(db, session_data)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
except Exception as e:
print(f"创建会话时出错: {e}")
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="创建会话失败")
@router.get("/assistant/{assistant_id}", response_model=List[SessionRead])
async def read_sessions_for_assistant(
assistant_id: str,
db: AsyncSession = Depends(get_db_session)
):
# Consider adding check if assistant exists first
return await session_service.get_sessions_by_assistant(db, assistant_id)
@router.get("/{session_id}", response_model=SessionRead)
async def read_session_by_id(
session_id: str,
db: AsyncSession = Depends(get_db_session)
):
session = await session_service.get_session(db, session_id)
if not session:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="找不到指定的会话")
return session
@router.delete("/{session_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_existing_session(
session_id: str,
db: AsyncSession = Depends(get_db_session)
):
deleted = await session_service.delete_session(db, session_id)
if not deleted:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="找不到指定的会话")