- Return empty list instead of crashing when avatar.db doesn't exist - Add is_available() check before each endpoint - 503 status when trying to access unavailable database
72 lines
2.3 KiB
Python
72 lines
2.3 KiB
Python
"""数字分身管理 API 端点"""
|
|
from fastapi import APIRouter, Query, HTTPException
|
|
|
|
from app.schemas import ApiResponse
|
|
from app.services.avatar_service import avatar_service, get_session, is_available
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("")
|
|
def list_avatars(
|
|
page: int = Query(default=1, ge=1),
|
|
page_size: int = Query(default=20, ge=1, le=100),
|
|
keyword: str = Query(default=None),
|
|
status: str = Query(default=None),
|
|
):
|
|
"""分页查询所有数字分身"""
|
|
if not is_available():
|
|
return ApiResponse(data={"total": 0, "page": page, "page_size": page_size, "items": []})
|
|
db = get_session()
|
|
try:
|
|
total, items = avatar_service.list_avatars(
|
|
db, page, page_size, keyword, status
|
|
)
|
|
return ApiResponse(
|
|
data={
|
|
"total": total,
|
|
"page": page,
|
|
"page_size": page_size,
|
|
"items": items,
|
|
}
|
|
)
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@router.get("/{avatar_id}")
|
|
def get_avatar(avatar_id: str):
|
|
"""获取单个数字分身详情"""
|
|
if not is_available():
|
|
raise HTTPException(status_code=503, detail="数字分身数据库尚未初始化")
|
|
db = get_session()
|
|
try:
|
|
data = avatar_service.get_avatar(db, avatar_id)
|
|
if not data:
|
|
raise HTTPException(status_code=404, detail="数字分身不存在")
|
|
return ApiResponse(data=data)
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@router.put("/{avatar_id}/status")
|
|
def update_avatar_status(avatar_id: str, body: dict):
|
|
"""更新数字分身状态(开机/关机)"""
|
|
status = body.get("status")
|
|
if status not in ("active", "inactive", "training"):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="status 必须是 active、inactive 或 training",
|
|
)
|
|
if not is_available():
|
|
raise HTTPException(status_code=503, detail="数字分身数据库尚未初始化")
|
|
db = get_session()
|
|
try:
|
|
data = avatar_service.update_status(db, avatar_id, status)
|
|
if not data:
|
|
raise HTTPException(status_code=404, detail="数字分身不存在")
|
|
msg = "已开机" if status == "active" else "已关机"
|
|
return ApiResponse(data=data, message=msg)
|
|
finally:
|
|
db.close()
|