gpt4 book ai didi

django - 从 django 提供压缩内容

转载 作者:可可西里 更新时间:2023-11-01 15:04:11 26 4
gpt4 key购买 nike

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

注意事项:

  • 我意识到这不是最佳实践,我很可能会使用 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

我是不是漏掉了什么?内容长度是否有可能是错误的?我还缺少其他 header 吗?

谢谢。

最佳答案

您也可以简单地使用 Django's GZip Middleware :

通过在 settings.py 中添加启用中间件:

MIDDLEWARE_CLASSES = (
"django.middleware.gzip.GZipMiddleware",
...
)

或者在返回特定响应之前执行此操作。在您的 views.py 中,dec 将是某个 url 的处理程序

from django.middleware.gzip import GZipMiddleware

gzip_middleware = GZipMiddleware()

def dec(request, *args, **kwargs):
response = func(request, *args, **kwargs)
return gzip_middleware.process_response(request, response)
return dec

注意:在使用 GZip 中间件之前,您应该确定您不会受到侧信道攻击。

Warning

Security researchers recently revealed that when compressiontechniques (including GZipMiddleware) are used on a website, the sitemay become exposed to a number of possible attacks. Before usingGZipMiddleware on your site, you should consider very carefullywhether you are subject to these attacks. If you’re in any doubt aboutwhether you’re affected, you should avoid using GZipMiddleware. Formore details, see the the BREACH paper (PDF) and breachattack.com.

还有:

Changed in Django 1.10: In older versions, Django’s CSRF protectionmechanism was vulnerable to BREACH attacks when compression was used.This is no longer the case, but you should still take care not tocompromise your own secrets this way.

关于django - 从 django 提供压缩内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/957577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com