I have a simply ListCreateApiView class in Django, for example:
class Test(ListCreateApiView):
def list(self, request, *args, **kwargs):
""" Some code which is creating excel file with openpyxl and send as response """
return excel_file
The problem is, when user send a request to get an excel_file, he must wait for 5-10 minutes till the file will return. User can't go to others urls untill file will not download (I have 10k objects in my db)
So, how can I add async here? I want that while the file is being formed, a person can follow other links of the application.
Thanks a lot!
CodePudding user response:
Django has some troubles with asynchrony, and async calls won't help you in cpu-intensive tasks, you'd better use some distributed task queue like celery
It will allow you to handle such heavy tasks (i.e. excel generation) in another thread without interrupting the main django thread. Follow the guide for integration with django.
Once installed and configured, create a task and fire it when a user reaches the endpoint: E.g.:
# tasks.py
from celery import shared_task
@shared_task
def generate_excel(*args, **kwargs):
...
# views.py
from tasks import generate_excel
class Test(ListCreateApiView):
def list(self, request, *args, **kwargs):
generate_excel.delay()
return Response()