Se agregaron estados y update a cada una de las tareas
This commit is contained in:
@@ -1,17 +1,19 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, Depends
|
||||
from fastapi.routing import APIRouter
|
||||
from celery_app import celery_app
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
from datetime import datetime
|
||||
from fastapi.responses import JSONResponse
|
||||
from typing import Dict, Any, List, Optional
|
||||
from api.api_v2.modules.authentication.services import get_current_user
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/async/task-status/{task_id}")
|
||||
async def get_task_status(task_id: str):
|
||||
@router.get("/async/task-status/{task_id}", response_model=Dict[str, Any])
|
||||
async def get_task_status(task_id: str, current_user: Dict = Depends(get_current_user)):
|
||||
"""
|
||||
Consulta el estado de una tarea agendada.
|
||||
|
||||
@@ -84,37 +86,9 @@ async def get_task_status(task_id: str):
|
||||
detail=f"Error al consultar el estado de la tarea: {str(e)}"
|
||||
)
|
||||
|
||||
@router.get("/async/tasks/active")
|
||||
async def get_active_tasks():
|
||||
"""
|
||||
Lista todas las tareas activas en el sistema.
|
||||
|
||||
Returns:
|
||||
JSONResponse con la lista de tareas activas
|
||||
"""
|
||||
try:
|
||||
# Obtener tareas activas desde Celery
|
||||
inspect = celery_app.control.inspect()
|
||||
active_tasks = inspect.active()
|
||||
scheduled_tasks = inspect.scheduled()
|
||||
|
||||
response_data = {
|
||||
"active_tasks": active_tasks or {},
|
||||
"scheduled_tasks": scheduled_tasks or {},
|
||||
"timestamp": datetime.utcnow().isoformat()
|
||||
}
|
||||
|
||||
return JSONResponse(content=response_data, status_code=200)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error al obtener tareas activas: {e}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Error al obtener tareas activas: {str(e)}"
|
||||
)
|
||||
|
||||
@router.delete("/async/task/{task_id}")
|
||||
async def cancel_task(task_id: str):
|
||||
@router.delete("/async/task/{task_id}", response_model=Dict[str, Any])
|
||||
async def cancel_task(task_id: str, current_user: Dict = Depends(get_current_user)):
|
||||
"""
|
||||
Cancela una tarea agendada.
|
||||
|
||||
|
||||
@@ -6,6 +6,81 @@ from ..common import create_error_response
|
||||
from core.config import settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
async def update_task(
|
||||
task_id: str,
|
||||
message: str,
|
||||
status: str,
|
||||
pedimento_id: str,
|
||||
organizacion_id: str,
|
||||
servicio: int
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Actualiza el estado de una tarea existente en el servicio de seguimiento.
|
||||
|
||||
Args:
|
||||
task_id: ID de la tarea de Celery
|
||||
message: Mensaje descriptivo del nuevo estado de la tarea
|
||||
status: Nuevo estado de la tarea
|
||||
pedimento_id: ID del pedimento asociado
|
||||
organizacion_id: ID de la organización
|
||||
servicio: ID del tipo de servicio (1-9)
|
||||
|
||||
Returns:
|
||||
Dict con la respuesta del servicio
|
||||
"""
|
||||
try:
|
||||
headers = {
|
||||
"Authorization": f"Token {settings.API_TOKEN}"
|
||||
}
|
||||
|
||||
# Construir el cuerpo de la petición
|
||||
update_data = {
|
||||
"task_id": task_id,
|
||||
"message": message,
|
||||
"status": status,
|
||||
"pedimento": pedimento_id,
|
||||
"organizacion": organizacion_id,
|
||||
"servicio": servicio
|
||||
}
|
||||
|
||||
logger.info(f"Actualizando tarea {task_id} con datos: {update_data}")
|
||||
|
||||
# Django requiere el slash final
|
||||
url = f"{settings.API_URL}/tasks/tasks/{task_id}/"
|
||||
logger.info(f"Actualizando tarea en: {url}")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.put(
|
||||
url,
|
||||
json=update_data,
|
||||
headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"Error al actualizar tarea {task_id}: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=create_error_response(
|
||||
message="Error al actualizar la tarea",
|
||||
errors=[str(e)],
|
||||
metadata={
|
||||
"task_id": task_id,
|
||||
"status": status
|
||||
}
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error inesperado al actualizar tarea {task_id}: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=create_error_response(
|
||||
message="Error inesperado al actualizar la tarea",
|
||||
errors=[str(e)],
|
||||
metadata={"task_id": task_id}
|
||||
)
|
||||
)
|
||||
|
||||
async def register_task(
|
||||
task_id: str,
|
||||
message: str,
|
||||
|
||||
Reference in New Issue
Block a user