- 使用HttpResponse
对于数据量不大的情况,可直接使用HttpResponse,此方式会将数据存入内存然后再输出:
import csv
import codecs
from django.http import HttpResponse
def download_csv_view(request):
response = HttpResponse(content_type='text/csv') # 指明下载的文件为csv格式
response.write(codecs.BOM_UTF8) # 指定编码类型
filename = "somefilename.csv"
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
"""如果文件名为中文且python版本为3.x,此处应写为:"""
# from django.utils.encoding import escape_uri_path