基於djnago框架的二進制流數據傳輸(提供較大文件的下載)
(1)數據源:
高質量圖片、視頻、音頻、文件、數據庫數據等。如果是數據庫文件,需要先讀取相應的數據,然后寫入表格在傳輸到前端以供下載!
(2)數據讀取:
利用yield函數生成器進行rb模式文件讀取操作
(3)數據傳輸:
通過StreamingHttpResponse()二進制流格式進行相應(from django.http.response import StreamingHttpResponse或者使用文件響應FileResponse)
如果除數中使用的有中文,需要通過quote()方法來確保中文不亂碼(from urllib.parse import quote)
文件的上傳見<Django之AJAX文件上傳>篇,python操作excel表格見<python操作excel----openpyxl模塊>或<xpython操作excel之xlwt與xlrd>
接口模式提供唯一碼的下載案例
1 import os 2 import openpyxl 3 from django.views import View 4 from django.http.response import StreamingHttpResponse 5 from urllib.parse import quote 6 7 8 class FileDownload(View): 9 def get(self, request, pk=None): 10 #查詢書庫獲相應字段數據 11 queryset = models.Surveys.objects.filter(pk=pk).only('unique_code')#only只顯示指定的字段 12 13 #創建excel寫入數據 14 book=openpyxl.Workbook() 15 table=book.create_sheet("唯一碼") 16 table.cell(1,1,"唯一碼")#openpyxl模塊創建的表索引都是從1開始 17 for index, code in enumerate(queryset.iterator(), 2):#查詢集合調用iterator方法成迭代器 18 table.cell(index, 1, code.unique_code) 19 book.save("唯一碼.xls") 20 21 22 #利用生成器進行文件讀取 23 def iter_file(path): 24 size=1024 25 with open(path, "rb")as f: 26 for data in iter(lambda :f.read(size), b''): 27 yield data 28 29 #以二進制形式進行數據流傳輸 30 response=StreamingHttpResponse(iter_file(os.path.join("唯一碼.xls")))#以二進制形式響應數據流 31 response['Content-Type'] = 'application/octet-stream'#瀏覽器不識別的也會自動下載 32 response['Content-Disposition'] = 'attachment; {}'.format( 33 "filename*=utf-8''{}".format(quote("唯一碼.xls"))#quote確保中文格式不亂碼 34 ) 35 return response