Returning CSV format from django-rest-framework?

前端 未结 4 2178
囚心锁ツ
囚心锁ツ 2021-02-13 22:23

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

4条回答
  •  一生所求
    2021-02-13 23:27

    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.

提交回复
热议问题