Ev. Ev. - 1 year ago 101
Python Question

Serving .json file to download

I am trying to serve a .json file through this function. The problem is that every time I make the request the browser displays the content instead of downloading the file.

I think it could be due to the fact that I am using

as a parameter for the HttpResponse object constructor. However, if I use only the file object, I get the following exception:

TypeError: cannot serialize '_io.BufferedRandom' object


invoices = models.Invoice.objects.filter(pk__in=document_ids).order_by(*ordering)
pcustomers = models.CustomerProxy.objects.all()
mixed_query = list(invoices) + list(pcustomers)

file = tempfile.NamedTemporaryFile(suffix='.json')
file.write(serializers.serialize('json', mixed_query).encode())

response = HttpResponse(file.read(), content_type='application/json')
response['Content-Disposition'] = 'attachment; filename=%s' % file.name
response['Content-Length'] = os.path.getsize(file.name)

except Exception:

return response

Answer Source

You don't need to go through the whole file generation process to create a downloadable file, you just need to add the Content-Disposition header normally. Does the code below work?

mixed_query = list(invoices) + list(pcustomers)
json_str = serializers.serialize('json', mixed_query))
response = HttpResponse(json_str, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename=export.json'