作为响应仅返回标头的csv文件

时间:2019-04-29 17:51:55

标签: python django python-3.x django-rest-framework

我需要在django中创建一个rest api,这将返回一个csv文件,该文件仅在其中包含标头,并且该文件是在运行时创建的。这是我的代码,不知道为什么它不发送文件,理想情况下此函数应返回csv文件,该文件具有标头作为文件名。

def get_template():

    fieldnames = ['id, rate_plan_name, test_cd, test_name, price, 
                  is_package, is_deleted']
    with open('templates.csv', 'w') as csvfile:
        wtr = csv.writer(csvfile, delimiter=',')
        wtr.writerow(fieldnames)

        response = HttpResponse('templates.csv', content_type='application/x-download')
        filename = "template_%s.csv" % (datetime.utcnow())
        content = "attachment; filename='%s'" % filename
        response['Content-Disposition'] = content
        return response

1 个答案:

答案 0 :(得分:0)

尝试这种方式(使用StreamingHttpResponse):

from django.http import StreamingHttpResponse
# this is simplified - you can use csv.reader/writer here;

# your views definition go here


csv_headers = 'id,reate_plan_name, ...'
buffer = StringIO()
buffer.write(csv_headers)
response = StreamingHttpResponse(buffer.getvalue(), content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="test.csv"'
return response

祝你幸福。