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

詳解django三種文件下載方式

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

一、概述

在實際的項目中很多時候需要用到下載功能,如導(dǎo)excel、pdf或者文件下載,當(dāng)然你可以使用web服務(wù)自己搭建可以用于下載的資源服務(wù)器,如nginx,這里我們主要介紹django中的文件下載。

實現(xiàn)方式:a標(biāo)簽+響應(yīng)頭信息(當(dā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)部使用迭代器進(jìn)行數(shù)據(jù)流傳輸。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

农安县| 青浦区| 西乌| 二手房| 工布江达县| 镇原县| 富源县| 衡阳县| 格尔木市| 平顶山市| 叶城县| 伊川县| 佛冈县| 武宣县| 宁蒗| 红安县| 达孜县| 珲春市| 泰兴市| 巴南区| 博乐市| 巴彦淖尔市| 龙山县| 古丈县| 福安市| 佳木斯市| 兴城市| 邮箱| 静乐县| 汾西县| 宜君县| 高安市| 榆树市| 江川县| 营山县| 鹤峰县| 依兰县| 玛沁县| 贞丰县| 河源市| 正定县|