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

69 lines
3.1 KiB
Python

# File: backend/app/api/v1/endpoints/assistants.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 # Import DB session dependency
from app.models.pydantic_models import AssistantRead, AssistantCreate, AssistantUpdate
from app.services.assistant_service import AssistantService # Import the class
router = APIRouter()
# --- Dependency Injection for Service and DB Session ---
# Service instance can be created per request or globally
# For simplicity, let's create it here, but pass db session to methods
assistant_service = AssistantService()
@router.post("/", response_model=AssistantRead, status_code=status.HTTP_201_CREATED)
async def create_new_assistant(
assistant_data: AssistantCreate,
db: AsyncSession = Depends(get_db_session) # Inject DB session
):
return await assistant_service.create_assistant(db, assistant_data)
@router.get("/", response_model=List[AssistantRead])
async def read_all_assistants(
db: AsyncSession = Depends(get_db_session)
):
return await assistant_service.get_assistants(db)
@router.get("/{assistant_id}", response_model=AssistantRead)
async def read_assistant_by_id(
assistant_id: str,
db: AsyncSession = Depends(get_db_session)
):
assistant = await assistant_service.get_assistant(db, assistant_id)
if not assistant:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="找不到指定的助手")
return assistant
@router.put("/{assistant_id}", response_model=AssistantRead)
async def update_existing_assistant(
assistant_id: str,
assistant_data: AssistantUpdate,
db: AsyncSession = Depends(get_db_session)
):
updated_assistant = await assistant_service.update_assistant(db, assistant_id, assistant_data)
if not updated_assistant:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="找不到指定的助手")
return updated_assistant
@router.delete("/{assistant_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_existing_assistant(
assistant_id: str,
db: AsyncSession = Depends(get_db_session)
):
# Handle potential error from service if trying to delete default
try:
deleted = await assistant_service.delete_assistant(db, assistant_id)
if not deleted:
# Check if it exists to differentiate 404 from 403 (or handle in service)
assistant = await assistant_service.get_assistant(db, assistant_id)
if assistant and assistant_id == 'asst-default':
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="不允许删除默认助手")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="找不到指定的助手")
except Exception as e: # Catch other potential DB errors
print(f"删除助手时出错: {e}")
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="删除助手失败")