在Heroku上使用Python启用压缩

11

谷歌现在因不够移动友好而对其进行惩罚。为了改进这种情况,谷歌建议我使用Gzip或Deflate压缩大量的Javascript。我在stackoverflow上看到了一些老的建议,但没有什么开箱即用的,我尝试搜索添加附加组件,但目前似乎没有任何东西可以解决问题。哪种压缩或启用gzip最不痛苦且最强大?

以下是谷歌建议我做的事情:

启用压缩 使用gzip或deflate压缩资源可以减少通过网络发送的字节数。 启用以下资源的压缩,以将它们的传输大小减少420KiB(减少74%)。

如果我正在使用Django,则可能更容易一些。

1个回答

11
Bottom Line Up Front - It's going to depend on the details of your app... Flask? Django? uWSGI? whitenoise and gunicorn seem to be the "go to" frameworks on Heroku, so that's what I used in the example below. It should translate to other frameworks.
The gist of the Google recommendation is about minimizing the number of bytes physically transferred from the server. There are several ways to do this, but among the highest impact, in no particular order -
- Minify JavaScript and CSS - Merge those files together - Manipulate cache behavior - Compress the HTTP response body
The quoted recommendation deals with compressing the response body, which is part of "content negotiation" in the HTTP specification. Ideally, the layer of the application that handles HTTP should handle this task. However, in Heroku, the HTTP layer is split between the platform itself and your application. Therefore, it's recommended to use a web framework like Flask or Django along with a lightweight web server like Gunicorn and a library like Whitenoise for serving static files.
To get started, add Whitenoise to your requirements.txt file and modify the WSGI application to have Whitenoise "wrap" your application.
from flask import Flask
from whitenoise import WhiteNoise

flapp = Flask(__name__)
#use a subdirectory for root, otherwise, the actual .py files can be served...
app = WhiteNoise(flap, root='./static/')

#define your routes:
@flapp.route('/')
def home_page():
    #etc. etc.

如果客户端发送了“Accept-Encoding: gzip”头,则会获取到gzip压缩内容。还有很多其他的参数可以调整,但这是一个起点。最终,您可能会担心CPU开销并希望预压缩文件;或者您可能会决定卸载静态文件是正确的方法。
使用类似cURL的工具验证,以获取静态文件:
curl -i -H "Accept-Encoding: gzip" http://yourapp.herokuapp.com/path/to/static

使用-i标志应该打印出头信息,它将向您展示请求的详细信息。请注意`Content-Encoding

HTTP/1.1 200 OK
Connection: keep-alive
Server: gunicorn/19.3.0
Date: Wed, 20 May 2015 15:33:35 GMT
Last-Modified: Wed, 20 May 2015 15:26:06 GMT
Content-Type: text/html; charset="utf-8"
Cache-Control: public, max-age=60
Access-Control-Allow-Origin: *
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 662
Via: 1.1 vegur

希望这可以帮助到您...

很棒的答案。WhiteNoise似乎是一个很好的想法 - 提供最佳实践,而不依赖于可能超出你掌控范围或(在我的情况下)经验范围的配置。 - bsa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接