Django 實(shí)現(xiàn)下載文件功能的示例
基于Django建立的網(wǎng)站,如果提供文件下載功能,最簡單的方式莫過于將靜態(tài)文件交給Nginx等處理,但有些時(shí)候,由于網(wǎng)站本身邏輯,需要通過Django提供下載功能,如頁面數(shù)據(jù)導(dǎo)出功能(下載動(dòng)態(tài)生成的文件)、先檢查用戶權(quán)限再下載文件等。因此,有必要研究一下文件下載功能在Django中的實(shí)現(xiàn)。
最簡單的文件下載功能的實(shí)現(xiàn)
將文件流放入HttpResponse對象即可,如:
def file_download(request): # do something... with open('file_name.txt') as f: c = f.read() return HttpResponse(c)
這種方式簡單粗暴,適合小文件的下載,但如果這個(gè)文件非常大,這種方式會(huì)占用大量的內(nèi)存,甚至導(dǎo)致服務(wù)器崩潰
更合理的文件下載功能
Django的HttpResponse對象允許將迭代器作為傳入?yún)?shù),將上面代碼中的傳入?yún)?shù)c換成一個(gè)迭代器,便可以將上述下載功能優(yōu)化為對大小文件均適合;而Django更進(jìn)一步,推薦使用 StreamingHttpResponse對象取代HttpResponse對象,StreamingHttpResponse對象用于將文件流發(fā)送給瀏覽器,與HttpResponse對象非常相似,對于文件下載功能,使用StreamingHttpResponse對象更合理。
因此,更加合理的文件下載功能,應(yīng)該先寫一個(gè)迭代器,用于處理文件,然后將這個(gè)迭代器作為參數(shù)傳遞給StreaminghttpResponse對象,如:
from django.http import StreamingHttpResponse 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 = "file_name.txt" response = StreamingHttpResponse(file_iterator(the_file_name)) return response
文件下載功能再次優(yōu)化
上述的代碼,已經(jīng)完成了將服務(wù)器上的文件,通過文件流傳輸?shù)綖g覽器,但文件流通常會(huì)以亂碼形式顯示到瀏覽器中,而非下載到硬盤上,因此,還要在做點(diǎn)優(yōu)化,讓文件流寫入硬盤。優(yōu)化很簡單,給StreamingHttpResponse對象的Content-Type和Content-Disposition字段賦下面的值即可,如:
response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="test.pdf"'
完整代碼如下:
from django.http import StreamingHttpResponse 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
具體導(dǎo)出文件格式
導(dǎo)出Excel表格
1. 首先是直接導(dǎo)出Excel表格
首先獲取要導(dǎo)出的數(shù)據(jù)、以列表方式保存。
然后將數(shù)據(jù)寫入到Excel,以流的方式返回到頁面下載。
import xlwt import io import json from django.http import HttpResponse def set_style(name, height, bold=False): style = xlwt.XFStyle() # 初始化樣式 font = xlwt.Font() # 為樣式創(chuàng)建字體 font.name = name # 'Times New Roman' font.bold = bold font.color_index = 000 font.height = height style.font = font # 設(shè)置單元格邊框 # borders= xlwt.Borders() # borders.left= 6 # borders.right= 6 # borders.top= 6 # borders.bottom= 6 # style.borders = borders # 設(shè)置單元格背景顏色 # pattern = xlwt.Pattern() # 設(shè)置其模式為實(shí)型 # pattern.pattern = pattern.SOLID_PATTERN # 設(shè)置單元格背景顏色 # pattern.pattern_fore_colour = 0x00 # style.pattern = pattern return style def write_excel(data, name, header): # 打開一個(gè)Excel工作簿 file = xlwt.Workbook() # 新建一個(gè)sheet,如果對一個(gè)單元格重復(fù)操作,會(huì)引發(fā)異常,所以加上參數(shù)cell_overwrite_ok=True table = file.add_sheet(name, cell_overwrite_ok=True) if data is None: return file # 寫標(biāo)題欄 row0 = [u'業(yè)務(wù)', u'狀態(tài)', u'北京', u'上海', u'廣州', u'深圳', u'狀態(tài)小計(jì)'] for i in range(0, len(row0)): table.write_merge(0, 0, i, i, row0[i], set_style('Times New Roman', 220, True)) table.write_merge(0, 2, 7, 9, "單元格合并", set_style('Times New Roman', 220, True)) """ table.write_merge(x, x + m, y, w + n, string, sytle) x表示行,y表示列,m表示跨行個(gè)數(shù),n表示跨列個(gè)數(shù),string表示要寫入的單元格內(nèi)容,style表示單元格樣式。其中,x,y,w,h,都是以0開始計(jì)算的。 """ l = 0 n = len(header) # 寫入數(shù)據(jù) for line in data: for i in range(n): table.write(l, i, line[header[i]]) l += 1 # 直接保存文件 # file.save("D:/excel_name.xls") # 寫入IO res = get_excel_stream(file) # 設(shè)置HttpResponse的類型 response = HttpResponse(content_type='application/vnd.ms-excel') from urllib import parse response['Content-Disposition'] = 'attachment;filename=' + parse.quote("excel_name") + '.xls' # 將文件流寫入到response返回 response.write(res) return response def get_excel_stream(file): # StringIO操作的只能是str,如果要操作二進(jìn)制數(shù)據(jù),就需要使用BytesIO。 excel_stream = io.BytesIO() # 這點(diǎn)很重要,傳給save函數(shù)的不是保存文件名,而是一個(gè)BytesIO流(在內(nèi)存中讀寫) file.save(excel_stream) # getvalue方法用于獲得寫入后的byte將結(jié)果返回給re res = excel_stream.getvalue() excel_stream.close() return res
2. 導(dǎo)出json文件
導(dǎo)出json文件不像Excel那么麻煩,只需要拼接json格式數(shù)據(jù)即可,直接導(dǎo)出到本地還是很簡單,但是導(dǎo)出到網(wǎng)頁,怎么像導(dǎo)出excel一樣不保存到本地,直接將流返回?
def write_json(data): try: json_stream = get_json_stream(data) response = HttpResponse(content_type='application/json') from urllib import parse response['Content-Disposition'] = 'attachment;filename=' + parse.quote("test") + '.json' response.write(json_stream) return response except Exception as e: print(e) def get_json_stream(data): # 開始這里我用ByteIO流總是出錯(cuò),但是后來參考廖雪峰網(wǎng)站用StringIO就沒問題 file = io.StringIO() data = json.dumps(data) file.write(data) res = file.getvalue() file.close() return res
3. 導(dǎo)出壓縮包
由于導(dǎo)出兩個(gè)文件無法同時(shí)都返回,所以考慮將這兩個(gè)文件放入包中,然后將包以流的方式返回。
思考?此時(shí)導(dǎo)出的是zip包中,我怎么將這兩個(gè)文件流寫入zip中,好像有點(diǎn)不太合理。后來在老大指導(dǎo)下先將要打包的文件保存到本地,打包到zip后,將本地的文件刪除,隨后將該zip文件流讀取,寫入到response,返回zip文件流。
def write_zip(e_data, j_data, export_name): try: # 保存到本地文件 # 返回文件名,注意此時(shí)保存的方法和前面導(dǎo)出保存的json、excel文件區(qū)別 j_name = write_json(j_data, export_name[1]) e_name = write_excel(e_data, export_name[1]) # 本地文件寫入zip,重命名,然后刪除本地臨時(shí)文件 z_name='export.zip' z_file = zipfile.ZipFile(z_name, 'w') z_file.write(j_name) z_file.write(e_name) os.remove(j_name) os.remove(e_name) z_file.close() # 再次讀取zip文件,將文件流返回,但是此時(shí)打開方式要以二進(jìn)制方式打開 z_file = open(z_name, 'rb') data = z_file.read() z_file.close() os.remove(z_file.name) response = HttpResponse(data, content_type='application/zip') from urllib import parse response['Content-Disposition'] = 'attachment;filename=' + parse.quote(z_name) return response except Exception as e: logging.error(e) print(e)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python使用re模塊實(shí)現(xiàn)信息篩選的方法
這篇文章主要介紹了Python使用re模塊實(shí)現(xiàn)信息篩選的方法,結(jié)合實(shí)例形式分析了Python正則re模塊進(jìn)行信息篩選操作的相關(guān)實(shí)現(xiàn)技巧及相關(guān)函數(shù)使用技巧,需要的朋友可以參考下2018-04-04python實(shí)現(xiàn)mask矩陣示例(根據(jù)列表所給元素)
這篇文章主要介紹了python實(shí)現(xiàn)mask矩陣示例(根據(jù)列表所給元素),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07如何使用Python進(jìn)行數(shù)據(jù)分析之方差分析詳解
這篇文章主要給大家介紹了關(guān)于如何使用Python進(jìn)行數(shù)據(jù)分析之方差分析的相關(guān)資料,方差分析是一種常用的對數(shù)據(jù)進(jìn)行分析的方法,用于兩個(gè)及兩個(gè)以上樣本均數(shù)和方差差別的顯著性檢驗(yàn),需要的朋友可以參考下2024-03-03