前言
基于Django建立的网站,如果提供文件下载功能,最简单的方式莫过于将静态文件交给Nginx等处理,但有些时候,由于网站本身逻辑,需要通过Django提供下载功能,如页面数据导出功能(下载动态生成的文件)、先检查用户权限再下载文件等。因此,有必要研究一下文件下载功能在Django中的实现。
完整代码
1 from django.http import StreamingHttpResponse
2
3 def big_file_download(request):
# do something...
def file_iterator(file_name, chunk_size=512):
with open(file_name) as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
the_file_name = "big_file.pdf"
response = StreamingHttpResponse(file_iterator(the_file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
return response
原文链接:http://www.jianshu.com/p/2ce715671340
通过此方法实现cmdb列表Excel导出
贴一段,将列表写入Excel的代码
def write_excel(project):
"""
生成excel
:param project:
:return:
"""
data = []
now = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M')
file_name = 'cmdb_excel_%s_' % project + now + '.xlsx'
workbook = xlsxwriter.Workbook('%s/%s' % (EXCEL_DIR,file_name))
check_and_mkdir(EXCEL_DIR)
worksheet = workbook.add_worksheet(u'%s 主机列表'%project)
worksheet.set_first_sheet()
worksheet.set_column('A:E', 15)
worksheet.set_column('K:K', 30)
worksheet.set_column('G:Z', 15)
title = ['这里是你的标题']
.....
alter_list = ['这里是你的内容']
..... 这里循环你的列表内容并添加到Data
format = workbook.add_format()
# 设置边框
format.set_border(1)
# 内容居中
format.set_align('center')
format.set_align('vcenter')
format.set_text_wrap()
format_title = workbook.add_format()
format_title.set_border(1)
# 标题背景色 灰色
format_title.set_bg_color('#cccccc')
format_title.set_align('center')
format_title.set_bold()
format_ave = workbook.add_format()
format_ave.set_border(1)
format_ave.set_num_format('0.00')
worksheet.write_row('A1', title, format_title)
i = 2
for alter_dic in data:
location = 'A' + str(i)
worksheet.write_row(location, alter_dic, format)
i += 1
workbook.close()
ret = (True, file_name)
return ret