Python 使用django下载附加了一些数据的大zip文件

Python 使用django下载附加了一些数据的大zip文件,python,django,nginx,mod-wsgi,Python,Django,Nginx,Mod Wsgi,我有一个像下面这样的视图片段,它从一个请求中获得一个zip文件名,我想在zip文件结束后附加一些字符串符号 @require_GET def download(request): ... skip response = HttpResponse(readFile(abs_path, sign), content_type='application/zip') response['Content-Length'] = os.path.getsize(abs_path) +

我有一个像下面这样的视图片段,它从一个请求中获得一个zip文件名,我想在zip文件结束后附加一些字符串
符号

@require_GET
def download(request):
    ... skip
    response = HttpResponse(readFile(abs_path, sign),  content_type='application/zip')
    response['Content-Length'] = os.path.getsize(abs_path) + len(sign)
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response
readFile
的功能如下:

def readFile(fn, sign, buf_size=1024<<5):
    f = open(fn, "rb")
    logger.debug("started reading %s" % fn)
    while True:
        c = f.read(buf_size)
        if c:
            yield c
        else:
            break
    logger.debug("finished reading %s" % fn)
    f.close()
    yield sign

默认情况下,Django不允许流式响应,因此它会缓冲整个响应。如果不允许,中间件将无法像现在这样运行

要获得您想要的行为,您需要使用

使用示例来自:


Django默认不允许流式响应,因此它会缓冲整个响应。如果不允许,中间件就无法像现在这样运行

要获得您想要的行为,您需要使用

使用示例来自:


这是一个替代HttpResponse的用例。

这是一个替代HttpResponse的用例。

最好使用FileResponse,它是StreamingHttpResponse的一个子类,针对二进制文件进行了优化。如果wsgi服务器提供,它将使用wsgi.file\u包装器,否则它会将文件分小段流出来

import os
from django.http import FileResponse
from django.core.servers.basehttp import FileWrapper


def download_file(request):
    _file = '/folder/my_file.zip'
    filename = os.path.basename(_file)
    response = FileResponse(FileWrapper(file(filename, 'rb')), content_type='application/x-zip-compressed')
    response['Content-Disposition'] = "attachment; filename=%s" % _file
    return response

最好使用FileRespose,它是StreamingHttpResponse的一个子类,针对二进制文件进行了优化。如果wsgi服务器提供,它将使用wsgi.file\u包装器,否则它会将文件以小块的形式流出来

import os
from django.http import FileResponse
from django.core.servers.basehttp import FileWrapper


def download_file(request):
    _file = '/folder/my_file.zip'
    filename = os.path.basename(_file)
    response = FileResponse(FileWrapper(file(filename, 'rb')), content_type='application/x-zip-compressed')
    response['Content-Disposition'] = "attachment; filename=%s" % _file
    return response

我刚刚尝试了
StreamingHttpResponse
,效果如我所料,非常感谢:)我刚刚尝试了
StreamingHttpResponse
,效果如我所料,非常感谢:)非常感谢,我收到了:)非常感谢,我收到了:)