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__)
app = WhiteNoise(flap, root='./static/')
@flapp.route('/')
def home_page():
如果客户端发送了“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
希望这可以帮助到您...