启用django的gzip压缩支持

django提供了gzip_page装饰器来处理对gzip的支持:

from django.views.decorators.gzip import gzip_page

@gzip_page
def viewFunc(request):
  return HttpResponse("hello"*100)


参考地址:https://docs.djangoproject.com/en/1.4/topics/http/decorators/#module-django.views.decorators.gzip

注意事项:这个gzip_page装饰器只有在你请求头中包含了gzip压缩请求的时候才会发挥作用,来压缩你的内容:

D:\curl-7.17.1>curl.exe -a 'remote_addr=x.x.x.x' http://x.x.x.x:8000/ -H Accept-Encoding:gzip,defalte >a.txt

这里的-H就指定了gzip压缩,所以返回的是压缩后的内容。

注意:

我自己测试时发现:当返回的内容太小时,会有不压缩的起情况。例如:

return HttpResponse([{'a':1}])


 


第二种方法:

def compress_string(s):
    import cStringIO, gzip
    zbuf = cStringIO.StringIO()
    zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
    zfile.write(s)
    zfile.close()
    return zbuf.getvalue()

使用gzip库来进行压缩。

posted @ 2013-05-22 14:07  jianhong  阅读(800)  评论(0编辑  收藏  举报