django开发系列:视图高级之CSV文件
生成CSV文件
有时候我们做的网站,需要将一些数据,生成有一个CSV文件给浏览器,并且是作为附件的形式下载下来。
生成小的CSV文件
用Python内置的csv模块来处理csv文件,并且使用HttpResponse来将csv文件返回回去。
import csv
from django.http import HttpResponse
def csv_view(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
# 下面类似于
# with open("xxx.csv", "w") as fp:
# csv.writer(fp)
writer = csv.writer(response) #HttpResponse重写了write方法,这里可以当成句柄使用
writer.writerow(['username', 'age', 'height', 'weight']