Junior — Middle
What actions would you take if request processing on a Django site takes a long time, for example, about a minute?
sobes.tech AI
Answer from AI
If processing a request in Django takes about a minute, it is too long for a synchronous web request, and the user may experience a timeout or poor UX. To solve this problem, you can:
- Offload long tasks to background processes using task queues, such as Celery with a RabbitMQ or Redis broker. The web request will trigger the task asynchronously and return a response immediately, with the result shown later.
- Use Django's asynchronous capabilities (starting from version 3.1) for request processing, if applicable.
- Optimize the processing logic itself: check database queries, caching, algorithms.
- To display progress or status of a background task, you can use WebSocket or periodic polling (AJAX).
Example of using Celery:
# tasks.py
from celery import shared_task
@shared_task
def long_running_task(param):
# long processing
return result
# views.py
from .tasks import long_running_task
from django.http import JsonResponse
def start_task(request):
task = long_running_task.delay(param)
return JsonResponse({'task_id': task.id})
Thus, the web server is not blocked, and the task is executed in the background.