最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解django三種文件下載方式

 更新時間:2018年04月06日 08:43:05   作者:W-D  
這篇文章主要介紹了詳解django三種文件下載方式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一、概述

在實際的項目中很多時候需要用到下載功能,如導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)文章

最新評論

固阳县| 永定县| 宣威市| 公主岭市| 疏勒县| 玛沁县| 内乡县| 安丘市| 平利县| 云霄县| 文化| 湘乡市| 高安市| 株洲县| 英德市| 衡水市| 会同县| 沈阳市| 五莲县| 高雄市| 长宁区| 朝阳县| 新邵县| 新源县| 自治县| 乐山市| 临潭县| 宝坻区| 黄浦区| 肥城市| 长岭县| 云林县| 体育| 南投市| 三台县| 确山县| 云安县| 双柏县| 巴青县| 革吉县| 项城市|