Django 关于StreamingHttpResponse与FileResponse文件下载的最优方法
#########################################################
 写在最前:
 自己和朋友成立了一个工作室——图灵数据科学工作室(VX:DataUpward):
 一是想和大家交个朋友;
 二是想帮助朋友们跳过我们遇到的坑,尽快找到解决办法。
======================================================
 工作室的运行也需要付出各种成本,“活下去”是我们的当务之急,如果大家有 :
- 数据分析(报告);
- 商业数据调研;
- 数据可视化展示;
- 数据爬虫;
- -数据模型开发;
- 机器学习算法挖掘
- …
 也欢迎和我们工作室开展合作~
 
Django下载文件最优的两种方法
1 StreamingHttpResponse下载
StreamingHttpResponse(streaming_content):流式相应,内容的迭代器形式,以内容流的方式响应。
注:
StreamingHttpResponse一般多现实在页面上,不提供下载。
以下为示例代码
def streamDownload(resquest):
	def file_iterator(filepath, chunk_size = 512):
		with open(filepath, 'rb') as f:
			while True:
				con = f.read(512)
				if con:
					yield con
				else:
					break
	filename = os.path.abspath(__file__) + 'test.txt'
	response = StreamingHttpResponse(file_iterator(filename)
	return response	
# 最后程序会将结果打印在显示器上
2 FileResponse下载
FileResponse(stream):以流形式打开后的文件
注:
FileResponse是StreamingHttpResponse的子类
以下为示例代码:
def homeproc2(request):
	cwd = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
	response = FileResponse(open(cwd + "/msgapp/templates/youfile", "rb"))
	response['Content-Type] = 'application/octet-stream'
	response['Content-Disposition'] = 'attachment;filename="filename"'
	return response
需要解释说明的是:
	response['Content-Type] = 'application/octet-stream'
	response['COntent-Disposition'] = 'attachment;filename="filename"'
Content-Type:用于指定文件类型。
COntent-Disposition:用于指定下载文件的默认名称,对,没错! “CO”两个字符都要大写。
两者都是MIME协议里面的标准类型。
 阿里云工作强度 585人发布
阿里云工作强度 585人发布