I have a working Django 1.8 site, and I want to add a RESTful API using django-rest-framework. I would like to support rendering to CSV and JSON formats, and am puzzling over ho
I think that a StreamingHttpResponse
should be the preferred way. With django-storages
and ViewSet
it looks more or less like this.
@action(detail=True, methods=["get"])
def download(self, request, pk=None):
f = self.get_object()
response = StreamingHttpResponse(
streaming_content=f.file.chunks(), content_type="text/csv"
)
response[
"Content-Disposition"
] = f'attachment; filename="{f.name}.csv"'
response.status_code = status.HTTP_200_OK
return response
Also, FileResponse
is basically a StreamingHttpResponse
with some headers etc so both are great for this use case.