async_tasks.py
2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""异步任务 API 路由"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.schemas.async_task import AsyncTaskCreate, AsyncTaskUpdate
from app.services import async_task_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/async-tasks", tags=["异步任务"])
@router.post("", status_code=201)
async def create_task(data: AsyncTaskCreate, db: AsyncSession = Depends(get_db)):
"""创建异步任务记录"""
return await async_task_service.create_task(db, data)
@router.put("/{task_id}")
async def update_task(
task_id: str, data: AsyncTaskUpdate, db: AsyncSession = Depends(get_db)
):
"""更新任务状态和结果"""
result = await async_task_service.update_task(db, task_id, data)
if not result:
raise HTTPException(status_code=404, detail="任务不存在")
return result
@router.get("/{task_id}")
async def get_task(task_id: str, db: AsyncSession = Depends(get_db)):
"""查询任务详情"""
result = await async_task_service.get_task(db, task_id)
if not result:
raise HTTPException(status_code=404, detail="任务不存在")
return result
@router.get("")
async def list_tasks(
page: int = Query(1, ge=1, description="页码"),
page_size: int = Query(20, ge=1, le=100, description="每页条数"),
status: Optional[str] = Query(None, description="按状态筛选:pending/processing/success/failed"),
task_id: Optional[str] = Query(None, description="按 celery_task_id 模糊搜索"),
db: AsyncSession = Depends(get_db),
):
"""分页查询异步任务列表(支持 status 筛选和 task_id 模糊搜索)"""
return await async_task_service.list_tasks(
db=db, page=page, page_size=page_size, status=status, task_id=task_id,
)
@router.post("/{task_id}/cancel")
async def cancel_task(task_id: str, db: AsyncSession = Depends(get_db)):
"""取消异步任务"""
try:
result = await async_task_service.cancel_task(db, task_id)
if not result:
raise HTTPException(status_code=404, detail="任务不存在")
return result
except ValueError as e:
raise HTTPException(status_code=409, detail=str(e))