Add Redis service and Celery configuration to Docker setup
- Introduced Redis service in both docker-compose files for production and development. - Updated web and celery services to use Redis as the broker and result backend. - Added necessary environment variables for Celery in settings.py. - Included new tasks and soil_data apps in Django settings and updated URL routing. - Updated requirements.txt to include Celery and Redis dependencies.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
from celery.result import AsyncResult
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from .celery_tasks import sample_task
|
||||
|
||||
|
||||
class TaskTriggerView(APIView):
|
||||
"""
|
||||
ثبت و اجرای تسک.
|
||||
POST با بدنه اختیاری: {"duration": 3} - مدت زمان تسک به ثانیه.
|
||||
"""
|
||||
|
||||
def post(self, request):
|
||||
duration = request.data.get("duration", 1)
|
||||
try:
|
||||
duration = int(duration)
|
||||
duration = max(1, min(duration, 60))
|
||||
except (TypeError, ValueError):
|
||||
duration = 1
|
||||
result = sample_task.delay(duration)
|
||||
return Response(
|
||||
{"code": 200, "msg": "success", "data": {"task_id": result.id}},
|
||||
status=status.HTTP_200_OK,
|
||||
)
|
||||
|
||||
|
||||
class TaskStatusView(APIView):
|
||||
"""
|
||||
وضعیت تسک بر اساس task_id.
|
||||
GET /api/tasks/<task_id>/status/
|
||||
"""
|
||||
|
||||
def get(self, request, task_id):
|
||||
result = AsyncResult(task_id)
|
||||
state = result.state
|
||||
data = {"task_id": task_id, "status": state}
|
||||
if state == "PENDING":
|
||||
data["message"] = "تسک در صف یا یافت نشد."
|
||||
elif state == "PROGRESS":
|
||||
data["progress"] = result.info
|
||||
elif state == "SUCCESS":
|
||||
data["result"] = result.result
|
||||
elif state == "FAILURE":
|
||||
data["error"] = str(result.result)
|
||||
return Response(
|
||||
{"code": 200, "msg": "success", "data": data},
|
||||
status=status.HTTP_200_OK,
|
||||
)
|
||||
Reference in New Issue
Block a user