惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google DeepMind News
Google DeepMind News
T
Tenable Blog
博客园_首页
S
Securelist
Spread Privacy
Spread Privacy
Google Online Security Blog
Google Online Security Blog
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
U
Unit 42
L
LINUX DO - 热门话题
量子位
T
Threat Research - Cisco Blogs
博客园 - 【当耐特】
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
Martin Fowler
Martin Fowler
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
Know Your Adversary
Know Your Adversary
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
T
The Blog of Author Tim Ferriss
aimingoo的专栏
aimingoo的专栏
V2EX - 技术
V2EX - 技术
T
Tailwind CSS Blog
月光博客
月光博客
Recent Announcements
Recent Announcements
G
Google Developers Blog
F
Full Disclosure
W
WeLiveSecurity
宝玉的分享
宝玉的分享
腾讯CDC
G
GRAHAM CLULEY
Vercel News
Vercel News
Simon Willison's Weblog
Simon Willison's Weblog
美团技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Help Net Security
Help Net Security

陈少文的网站

巨变与机遇的未来十年 Kubernetes 平台管理软件压力测试方案 使用镜像部署 Hexo 静态页面 终于等到你 - GitHub 镜像仓库服务(ghcr.io) 一起来学 Go --(6)Interface 一起来学 Go --(5)Goroutine 和 Channel 什么是函数式编程 如何在 Kubernetes 集群集成 Kata 柯里化与偏函数 使用 PyGithub 自动创建 Label 软件产品是团队能力的输出 Helm 2 、Helm 3 比较 IoT 变现 Kubernetes 中的 DNS 服务 国内的 Helm 镜像源 Harbor 使用自签证书支持 Https 访问 DevOps 工具链之 Prow 如何使用 kfctl 安装 Kubeflow VS Code 无法下载 Go 插件的工具包 工程师更应具有服务精神 你不知道的 Docker 使用技巧 使用 Docker 运行 Tensorflow 论中国 什么是左移 如何清空 Git 仓库全部历史记录 一禅小和尚 有风吹过厨房 时间的玫瑰 如何在 CentOS 安装 GPU 驱动 开发 Tips(19) 使用 Velero 备份 Kubernetes 集群 Kubernetes Cheat Sheet 开发 Tips(18) 如何构建一个 Java 工程 开发 Tips(17) KubeSpray 安装 Kubernetes 报错 ip in ansible_all_ipv4_addresses 基于 Kubernetes 和 Jenkins 搭建自动化测试系统 在 Kubernetes 上动态创建 Jenkins Slave 使用 Jenkins 进行服务拨测 开发 Tips(16) Kubernetes 签发 Ingress 证书及日常故障运维 Kubernetes 中 Deployment 的基本操作 Kubernetes 中的证书 如何使用 KubeBuilder 开发一个 Operator Kubernetes 1.6.0 安装问题汇总 镜像管理工具 -- Harbor 开发 Tips(15) Docker 如何拉取镜像 开发 Tips(14) 使用 Helm 安装 harbor 开发 Tips(13) 使用 S2I 构建云原生应用 在 Kubernetes 中使用 emptyDir、hostPath、localVolume 开发 Tips(12) 开发 Tips(11) 代码质量分析工具 SonarQube 使用 Kubeadm 安装 Kubernetes 集群 一起来学 Go --(4)常用函数 Kubernetes 中的 Ceph Kubernetes 之 Volumes Kubernetes 之 Labels、Selectors 开发 Tips(10) 开源正在重构商业模式 Kubernetes 之网络 Kubernetes 之 API 使用 Helm 和 Operator 快速部署 Prometheus Kubernetes 复杂有状态应用管理框架 -- Operator Kubernetes 的包管理器 -- Helm 一起来学 Go --(3)Go Modules 如何一步一步地优化博客方案 kubectl 实用指南 Kubernetes 中的基本概念 搭建远程 Kubernetes 开发环境 大公司和小公司的 ToB 思路 开发 Tips(9) Go 入门指南 一起来学 Go --(2)数据与逻辑结构 如何预防 Web 富文本中的 XSS 攻击 django-xss-cleaner 云工作时代 一起来学 Go --(1)背景与特点 SaaS 开发团队的不同阶段 你不知道的 Git 使用技巧 输出既服务 微服务设计 继续奔跑 开发 Tips(8) 从账户安全到二次验证 Django 性能之数据库查询优化 Django 性能之分库分表 敏捷开发之研发流程 打造一致性的团队 开发 Tips(7) Pytest 进阶学习之 Mock PaaS 部署之 buildpack Go 开发配置 领域输出才是 PaaS 的核心竞争力 Pytest 入门学习 开发 Tips(6) 如何使用 Jenkins、Docker、GitLab 搭建 Django 自动化部署流程
Django 大文件传输
微信公众号 · 2017-09-27 · via 陈少文的网站

Please enable Javascript to view the contents

1. 直接返回文件

如果静态文件在工程根目录的 media/test.zip,需要先将文件读入内存,再进行传输。代码如下:

settings.py 配置

1
2
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media/')

yourapp/views.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.conf import settings
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage

def download_file_direct_from_file(request):
  file_system = FileSystemStorage(settings.MEDIA_ROOT)
  file_name = 'test.zip'
  with file_system.open(file_name) as f:
      response = HttpResponse(f)
      response['Content-Type'] = 'application/%s' % file_name.split('.')[-1]
      response['Content-Disposition'] = 'attachment; filename="%s"'% file_name
  return response

如果是从 API 调用,第三方获取的文件,那么只需要将 with file_system.open(file_name) as f 中的变量,f,赋值为请求到的文件体即可,如:f = requests.get(url).content。下面的代码示例,就不一一说明了,仅以下载本地文件为例。

2. 返回流式的文件

Django 的 HttpResponse 对象支持以迭代器作为初始化参数,将文件对象替换为一个迭代器或生成器,可以优化 Django 对大文件的处理。同时,Django 提供了 StreamingHttpResponse 对象取代 HttpResponse 对象,以支持以流的形式发送文件给浏览器。

可以自己实现一个迭代器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.conf import settings
from django.http import StreamingHttpResponse

def download_file_direct(request):
    file_name = 'test.zip'
    full_path_file_name = ''.join([settings.MEDIA_ROOT, file_name])

    def file_read(full_path_name, chunk_size=512):
        with open(full_path_name, 'rb') as f:
            while True:
                chunks = f.read(chunk_size)
                if chunks:
                    yield chunks
                else:
                    break

    response = StreamingHttpResponse(file_read(full_path_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=%s' % (file_name)
    return response

也可以使用 Django 提供的 FileWrapper 类来迭代器化文件对象。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.servers.basehttp import FileWrapper
from django.http import StreamingHttpResponse

def download_file_chunk_from_file(request):
    file_system = FileSystemStorage(settings.MEDIA_ROOT)
    file_name = 'test.zip'
    response = StreamingHttpResponse(FileWrapper(file_system.open(file_name, 'rb'), 512))
    response['Content_Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment; filename=%s' % file_name
    return response

3. 利用 sendfile 机制

Django 处理文件时,需要将文件内容读入到内存,再将内存中的内容发送给浏览器。Django 对文件的转发处理能力远比不上 Nginx。比较好的方法是,使用 Django 做权限判断,然后设置 Nginx 转发文件。

sendfile 是一种高性能网络 IO 的方式,利用操作系统内核的 sendfile 调用,可以将文件内容直接推送到网卡的 buffer,避免了应用层读写文件的开销。而在 Nginx 中,可以通过 X-Accel-Redirect 的特性来实现 sendfile 机制的文件处理。

Nginx 配置

1
2
3
4
location /media {
    internal;
    alias /var/www/my_django_project_root/media;
}

views.py

1
2
3
4
5
6
7
8
9
from django.conf import settings
from django.http import HttpResponse

def download_file_from_nginx(request):
    file_name = 'test.zip'
    response['Content_Type']='application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=%s' % (file_name)
    response['X-Accel-Redirect'] = '/media/%s' % file_name
    return response

4. 参考


微信公众号