详解django三种文件下载方式

yipeiwu_com5年前Python基础

一、概述

在实际的项目中很多时候需要用到下载功能,如导excel、pdf或者文件下载,当然你可以使用web服务自己搭建可以用于下载的资源服务器,如nginx,这里我们主要介绍django中的文件下载。

实现方式:a标签+响应头信息(当然你可以选择form实现)

<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' #设置头信息,告诉浏览器这是个文件
  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

使用总结

三种http响应对象在django官网都有介绍.入口:https://docs.djangoproject.com/en/1.11/ref/request-response/

推荐使用FileResponse,从源码中可以看出FileResponse是StreamingHttpResponse的子类,内部使用迭代器进行数据流传输。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用python实现BLAST

使用python实现BLAST

最近在自学python,又用python实现了一下BLAST。 这次更新了打分函数如下,空位罚分改为-5,但不区分gap open 和 gap extend。 ''''' @au...

在Django的URLconf中使用命名组的方法

在我们想要捕获的URL部分上加上小括号,Django 会将捕获的文本作为位置参数传递给视图函数。 在更高级的用法中,还可以使用 命名 正则表达式组来捕获URL,并且将其作为关键字参数传给...

python将txt等文件中的数据读为numpy数组的方法

实际中,很多数据都是存为txt文件、csv文件等,但是在程序中处理的时候numpy数组或列表是最方便的。本文简单介绍读入txt文件以及将之转化为numpy数组或列表的方法。 1 将txt...

python类继承用法实例分析

本文实例讲述了python类继承用法。分享给大家供大家参考。具体如下: help('object') # test class Class1(object): """ Cla...

python共享引用(多个变量引用)示例代码

python共享引用(多个变量引用)示例代码

复制代码 代码如下:a = 3b = a 先上图(图1)吧,大家一看就一目了然了: 变量名和对象,在运行赋值语句b = a之后,变量a,b都指向了对象3的内存空间.假设这时执行 a =...