django zip

from django.utils.text import compress_sequence, compress_string
compressed_content = compress_string(xml_str)
response = HttpResponse() response['Content-Encoding']='gzip'
response.content = compressed_content
response['Content-Length'] = str(len(response.content))

return response'''

https://github.com/django/django/blob/master/django/middleware/gzip.py

代码如上,如果你的nginx配置了gzip on

那么以上代码可以删除

因为nginx会压缩的,你不用再用代码压缩了


如何在线压缩string:

import zlib

output_string = zlib.compress('some_bytes_to_compress')

And then you can decompress it (assuming Python):

decompressed_string = zlib.decompress(output_string)


在线生成zip压缩文件

import zipfile
from cStringIO import StringIO
from django.utils.httpwrappers import HttpResponse

def view_that_returns_zipped_file(request):
    response = HttpResponse(mimetype='application/zip')
    response['Content-Disposition'] = 'filename=all_things.zip'
    #first assemble your files
    files = []
    for thing in Thing.objects.all():
        files.append(("%s.pdf" % (thing.id,), thing.biggish_file()))
    #now add them to a zip file
    #note the zip only exist in memory as you add to it
    buffer = StringIO()
    zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED)
    for name, f in files:
        zip.writestr(name, f)
    zip.close()
    buffer.flush()
    #the import detail--we return the content of the buffer
    ret_zip = buffer.getvalue()
    buffer.close()
    response.write(ret_zip)
    return response


HTTP ZIP协议文档:

http://www.cnblogs.com/TankXiao/archive/2012/11/13/2749055.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值