Django Zip
本文讲述通过Rest-API方式下载zip文件
1.运行环境
a)Django 1.11.20
b)python 3.7.1 x64
c)djangorestframework 3.11.0
2.流程分析
首先zip文件是不需要提前存在的,用户可以选择将哪些文件打包成zip文件,然后下载,可以采用两种方式
1)待打包文件放入memory中
2)打包文件放到disk
对于大文件我们可以采用2)的方式,不占用太多资源
3.用到的module
a)FileWrapper
b)tempfile
c)zipfile
4.Code
from rest_framework.generics import GenericAPIView
from django.http import HttpResponse
from wsgiref.util import FileWrapper
# from django.core.servers.basehttp import FileWrapper
import tempfile
import zipfile
class DownLoadZipFile(GenericAPIView):
def __init__(self):
super(GenericAPIView, self).__init__()
def post(self, request):
"""
API 'POST' method for send command operation
:param request:
:return response:
"""
# for test
file_path_list = [
{'file_name': 'file1', 'file_path': 'full_path'}
]
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for file_path_dict in file_path_list:
file_path = file_path_dict.get('file_path', None)
file_name = file_path_dict.get('file_name', None)
archive.write(file_path, file_name) # TODO need check file exist or not
archive.close()
lenth = temp.tell()
temp.seek(0)
wrapper = FileWrapper(temp)
# Using HttpResponse
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=archive.zip'
response['Content-Length'] = lenth # temp.tell()
return response
5.说明
from wsgiref.util import FileWrapper
# from django.core.servers.basehttp import FileWrapper
Django版本不同可能import方式不同,对于我们的环境上面一条导入成功。
temp = tempfile.TemporaryFile()
会在C:\Users\<username>\AppData\Local\Temp\ 下创建临时文件
至于seek/tell用法,可参考seek/tell