Currently, I am using DRF version '3.9.2'. I was doing some CSV export from models synchronously. Sample of the code blocks explained as below:
urls.py
from django.urls import path
urlpatterns = [
path('api/users-csv-export/', UsersExportAsCSV.as_view())
]
views.py
from rest_framework.views import APIView
def get_users_data():
queryset = User.objects.only('first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth')
fields = ['first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth']
titles = ['First Name', 'Last Name', 'Date Added', 'Email', 'Gender', 'Date of Birth']
file_name = 'users'
return queryset, fields, titles, file_name
class UsersExportAsCSV(APIView):
def get(self, request):
users = get_users_data()
data = export_to_csv(queryset=users[0], fields=users[1], titles=users[2], file_name=users[3])
return data
utils.py
def export_to_csv(queryset, fields, titles, file_name):
"""
will export the model data in the form of csv file
:param queryset: queryset that need to be exported as csv
:param fields: fields of a model that will be included in csv
:param titles: title for each cell of the csv record
:param file_name: the exported csv file name
:return:
"""
model = queryset.model
response = HttpResponse(content_type='text/csv')
# force download
response['Content-Disposition'] = 'attachment; filename={}.csv'.format(file_name)
# the csv writer
writer = csv.writer(response)
if fields:
headers = fields
if titles:
titles = titles
else:
titles = headers
else:
headers = []
for field in model._meta.fields:
headers.append(field.name)
titles = headers
# Writes the title for the file
writer.writerow(titles)
# write data rows
for item in queryset:
writer.writerow([nested_getattr(item, field) for field in headers])
return response
As the data grows the request-response cycle becomes heavier. To prevent this request blocking other requests Threading vs Async task which one is preferable? Is there any good idea about optimizing the request-response cycle.
Here the user has to wait until whole the exporting works and download complete. The desired result here is that whenever the user visits the URL then the instant response of "file being generated" and generating and downloading the file in the background.
Any help on this topic will be highly appreciated.