文件下載(StreamingHttpResponse流式輸出)
HttpResponse會直接使用迭代器對象,將迭代器對象的內容存儲成字符串,然后返回給客戶端,同時釋放內存。可以當文件變大看出這是一個非常耗費時間和內存的過程。
而StreamingHttpResponse是將文件內容進行流式傳輸,數據量大可以用這個方法。
參考:
http://blog.csdn.net/gezi_/article/details/78176943?locationNum=10&fps=1
https://yq.aliyun.com/articles/44963
demo:下載download.txt
from django.shortcuts import render
from django.http import StreamingHttpResponse
from django_demo.settings import BASE_DIR
# Create your views here.
def download(request):
def filetostream(filename,streamlength=512):
file=open(filename,'rb')
while True:
stream=file.read(streamlength)
if stream:
yield stream
else:
break
print(BASE_DIR)
response = StreamingHttpResponse(filetostream(BASE_DIR+'/file_download_demo/download.txt'))
# response=StreamingHttpResponse(filetostream('download.txt')) # 無法直接讀取當前文件夾下文件,必須用settings.py中的BASE_DIR確定絕對路徑,為什么?
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="download.txt"'
return response