詳解django三種文件下載方式
一、概述
在實際的項目中很多時候需要用到下載功能,如導excel、pdf或者文件下載,當然你可以使用web服務(wù)自己搭建可以用于下載的資源服務(wù)器,如nginx,這里我們主要介紹django中的文件下載。
實現(xiàn)方式:a標簽+響應(yīng)頭信息(當然你可以選擇form實現(xiàn))
<div class="col-md-4"><a href="{% url 'download' %}" rel="external nofollow" >點我下載</a></div>
方式一:使用HttpResponse
路由url:
url(r'^download/',views.download,name="download"),
views.py代碼
from django.shortcuts import HttpResponse
def download(request):
file = open('crm/models.py', 'rb')
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream' #設(shè)置頭信息,告訴瀏覽器這是個文件
response['Content-Disposition'] = 'attachment;filename="models.py"'
return response
方式二:使用StreamingHttpResponse
其他邏輯不變,主要變化在后端處理
from django.http import StreamingHttpResponse
def download(request):
file=open('crm/models.py','rb')
response =StreamingHttpResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="models.py"'
return response
方式三:使用FileResponse
from django.http import FileResponse
def download(request):
file=open('crm/models.py','rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition']='attachment;filename="models.py"'
return response
使用總結(jié)
三種http響應(yīng)對象在django官網(wǎng)都有介紹.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/
推薦使用FileResponse,從源碼中可以看出FileResponse是StreamingHttpResponse的子類,內(nèi)部使用迭代器進行數(shù)據(jù)流傳輸。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
執(zhí)行python腳本并傳入json數(shù)據(jù)格式參數(shù)方式
這篇文章主要介紹了執(zhí)行python腳本并傳入json數(shù)據(jù)格式參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
python 判斷網(wǎng)絡(luò)連通的實現(xiàn)方法
下面小編就為大家分享一篇python 判斷網(wǎng)絡(luò)連通的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
python執(zhí)行l(wèi)inux系統(tǒng)命令的三種方式小結(jié)
本文介紹三種在python執(zhí)行l(wèi)inux命令的方式,三種方式都是基于python的標準庫實現(xiàn),因此不需要額外安裝第三方庫,具有一定的參考價值,感興趣的可以了解一下2024-02-02
Python中bytes字節(jié)串和string字符串之間的轉(zhuǎn)換方法
python中字節(jié)字符串不能格式化,獲取到的網(wǎng)頁有時候是字節(jié)字符串,需要轉(zhuǎn)化后再解析,下面這篇文章主要給大家介紹了關(guān)于Python中bytes字節(jié)串和string字符串之間的轉(zhuǎn)換方法,需要的朋友可以參考下2022-01-01
手動實現(xiàn)把python項目發(fā)布為exe可執(zhí)行程序過程分享
這篇文章主要介紹了手動實現(xiàn)把python項目發(fā)布為exe可執(zhí)行程序過程分享,本文使用C語言實現(xiàn)了一個簡潔的Python打包程序,需要的朋友可以參考下2014-10-10

