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對(duì)象即可,如:
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對(duì)象允許將迭代器作為傳入?yún)?shù),將上面代碼中的傳入?yún)?shù)c換成一個(gè)迭代器,便可以將上述下載功能優(yōu)化為對(duì)大小文件均適合;而Django更進(jìn)一步,推薦使用 StreamingHttpResponse對(duì)象取代HttpResponse對(duì)象,StreamingHttpResponse對(duì)象用于將文件流發(fā)送給瀏覽器,與HttpResponse對(duì)象非常相似,對(duì)于文件下載功能,使用StreamingHttpResponse對(duì)象更合理。
因此,更加合理的文件下載功能,應(yīng)該先寫一個(gè)迭代器,用于處理文件,然后將這個(gè)迭代器作為參數(shù)傳遞給StreaminghttpResponse對(duì)象,如:
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對(duì)象的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,如果對(duì)一個(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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python連接es筆記之創(chuàng)建和刪除操作示例詳解
這篇文章主要為大家介紹了Python連接es筆記之創(chuàng)建和刪除操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
使用Python創(chuàng)建一個(gè)視頻管理器并實(shí)現(xiàn)視頻截圖功能
在這篇博客中,我將向大家展示如何使用 wxPython 創(chuàng)建一個(gè)簡單的圖形用戶界面 (GUI) 應(yīng)用程序,該應(yīng)用程序可以管理視頻文件列表、播放視頻,并生成視頻截圖,我們將逐步實(shí)現(xiàn)這些功能,并確保代碼易于理解和擴(kuò)展,感興趣的小伙伴跟著小編一起來看看吧2024-08-08
Windows下安裝python MySQLdb遇到的問題及解決方法
這篇文章主要介紹了Windows下安裝python MySQLdb遇到的問題及解決方法,需要的朋友可以參考下2017-03-03
pandas按行按列遍歷Dataframe的三種方式小結(jié)
本文主要介紹了pandas按行按列遍歷Dataframe,主要介紹了三種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11
基于高德地圖API在Python中實(shí)現(xiàn)地圖功能的方法示例詳解
本文介紹在高德開放平臺(tái)中,申請、獲取地圖API的Key的方法,同時(shí)通過簡單的Python代碼,調(diào)取API信息,對(duì)所得Key的可用性加以驗(yàn)證,感興趣的朋友一起看看吧2025-01-01
Python利用matplotlib實(shí)現(xiàn)繪制密度散點(diǎn)圖
這篇文章主要介紹了如何基于Python語言的matplotlib模塊,對(duì)Excel表格文件中的指定數(shù)據(jù)加以密度散點(diǎn)圖繪制的方法,有需要的小伙伴可以參考下2024-04-04
Python實(shí)現(xiàn)無痛修改第三方庫源碼的方法詳解
很多時(shí)候,我們下載的 第三方庫 是不會(huì)有需求不滿足的情況,但也有極少的情況,第三方庫 沒有兼顧到需求,本文將介紹幾個(gè)修改源碼的操作,大家可以根據(jù)需求進(jìn)行選擇2025-03-03

