51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
from fastapi import APIRouter, BackgroundTasks
|
|
from app.tasks.tasks import add_numbers, long_running_task
|
|
from app.core.logging import log
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.get("/")
|
|
async def root():
|
|
"""Root endpoint"""
|
|
log.info("Root endpoint accessed")
|
|
return {"message": "FastAPI Celery Example"}
|
|
|
|
|
|
@router.post("/add")
|
|
async def add_task(x: int, y: int, background_tasks: BackgroundTasks):
|
|
"""Submit an addition task to Celery"""
|
|
log.info(f"Submitting addition task: {x} + {y}")
|
|
|
|
# Submit task to Celery
|
|
task = add_numbers.delay(x, y)
|
|
|
|
return {"task_id": task.id, "status": "submitted", "message": f"Addition task submitted: {x} + {y}"}
|
|
|
|
|
|
@router.get("/result/{task_id}")
|
|
async def get_result(task_id: str):
|
|
"""Get the result of a Celery task"""
|
|
from app.core.celery_app import celery_app
|
|
|
|
log.info(f"Checking result for task: {task_id}")
|
|
|
|
task_result = celery_app.AsyncResult(task_id)
|
|
|
|
if task_result.state == "PENDING":
|
|
return {"task_id": task_id, "status": "pending"}
|
|
elif task_result.state == "SUCCESS":
|
|
return {"task_id": task_id, "status": "success", "result": task_result.result}
|
|
else:
|
|
return {"task_id": task_id, "status": "failure", "error": str(task_result.info)}
|
|
|
|
|
|
@router.post("/long-task")
|
|
async def long_task(duration: int = 10):
|
|
"""Submit a long running task"""
|
|
log.info(f"Submitting long running task for {duration} seconds")
|
|
|
|
task = long_running_task.delay(duration)
|
|
|
|
return {"task_id": task.id, "status": "submitted", "message": f"Long running task submitted for {duration} seconds"}
|