django提供文件下载,若果文件较小,解决办法是先将要传送的内容全生成在内存中,然后再一次性传入响应对象中,如下:
但是当文件内容很大时,这种方法就不行了,
[Python]
纯文本查看
复制代码
1 2 3 4 | def file_download(request): # do something... content = open("file_name", "rb").read() return HttpResponse(content) |
但是当文件内容很大时,这种方法就不行了,
django文档中提到,可以向HttpResponse传递一个迭代器,流式的向客户端传递数据,如下:
[Python]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 12 | def read_file(filename, buf_size=4096): with open(filename, "rb") as f: while True: content = f.read(buf_size) if content: yield content else: breakdef big_file_download(request): filename = "filename" response = HttpResponse(read_file(filename)) return response |
更多技术资讯可关注:gzitcast