从django提供gzip压缩内容 [英] Serving gzipped content from django

查看:657
本文介绍了从django提供gzip压缩内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django中提供文本/ html页面的gzip压缩版本,但Firefox告诉我内容编码错误。

I'm trying to serve a gzipped version of a text/html page in Django, but Firefox is telling me there's a content encoding error.

注意:


  • 我意识到这不是最佳做法,我很可能会使用mod_gzip。这只是一个了解正在发生的事情的学习练习。

  • 我知道Django gzip中间件 - 它存在二进制文件问题。

这是我的代码:

rendered_page =  zlib.compress(template.render(context).encode('utf-8'))

response = HttpResponse(rendered_page)
response['Content-Encoding'] = 'gzip'
response['Content-Length'] = len(rendered_page)
return response

我在这里遗漏了什么吗?内容长度是否有可能错误?是否还有我缺少的额外标题?

Am I missing something here? Is it possible that the content length is wrong? Are there additional headers I'm missing?

谢谢。

推荐答案

zlib 有点太低级了。以下是GZip中间件本身的用法(参见 django.utils中的compress_string) .text.py ):

zlib is a bit too low-level for this purpose. Here's how the GZip middleware itself does it (see compress_string in django.utils.text.py):

import cStringIO, gzip
zbuf = cStringIO.StringIO()
zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
zfile.write(template.render(context).encode('utf-8'))
zfile.close()

compressed_content = zbuf.getvalue()
response = HttpResponse(compressed_content)
response['Content-Encoding'] = 'gzip'
response['Content-Length'] = str(len(compressed_content))
return response

GZip使用zlib,但是在它自己的zlib上产生的内容不正确地编码为浏览器看到'gzip'作为内容编码。希望有所帮助!

GZip uses zlib, but on its own zlib produces content that's improperly encoded for a browser seeing 'gzip' as the content encoding. Hope that helps!

这篇关于从django提供gzip压缩内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆