Returning CSV format from django-rest-framework?

前端 未结 4 2180
囚心锁ツ
囚心锁ツ 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:02

    If you just need to download CSV (without Model serialization etc)

    import csv
    from django.http import HttpResponse
    from rest_framework.views import APIView
    
    
    class CSVviewSet(APIView):
    
        def get(self, request, format=None):
            response = HttpResponse(content_type='text/csv')
            response['Content-Disposition'] = 'attachment; filename="export.csv"'
            writer = csv.DictWriter(response, fieldnames=['emp_name', 'dept', 'birth_month'])
            writer.writeheader()
            writer.writerow({'emp_name': 'John Smith', 'dept': 'Accounting', 'birth_month': 'November'})
            writer.writerow({'emp_name': 'Erica Meyers', 'dept': 'IT', 'birth_month': 'March'})
            return response
    

提交回复
热议问题