flask-compress的使用方法
參考:https://github.com/shengulong/flask-compress
1、Content-Encoding是HTTP協議的響應報文頭,一般形式如:Content-Encoding:gzip,deflate,compress
deflate(RFC1951):一種壓縮算法,使用LZ77和哈弗曼進行編碼;
zlib(RFC1950):一種格式,是對deflate進行了簡單的封裝;
gzip(RFC1952):一種格式,也是對deflate進行的封裝.
可以看出deflate是最核心的算法,而zlib和gzip格式的區別僅僅是頭部和尾部不一樣,而實際的內容都是deflate編碼的,即:
gzip = gzip頭(10字節) + deflate編碼的實際內容 + gzip尾(8字節)
zlib = zlib頭 + deflate編碼的實際內容 + zlib尾
2、flask-compress是用來壓縮響應內容的,當然更好的解決方案是使用nginx做代理,使用nginx的自動壓縮靜態文件壓縮功能,需要對nginx進行配置
工作原理:flask-compress會給http響應增加兩個http頭:vary、content-encoding,並壓縮響應的數據。
How it works
Flask-Compress both adds the various headers required for a compressed response and gzips the response data. This makes serving gzip compressed static files extremely easy.
Internally, every time a request is made the extension will check if it matches one of the compressible MIME types and will automatically attach the appropriate headers.
3、安裝 pip install flask-compress
or, if you want the latest github version:
$ pip install git+git://github.com/libwilliam/flask-compress.gi
4、使用
1 from flask import Flask 2 from flask_compress import Compress 3 4 app = Flask(__name__) 5 Compress(app)
1 from flask import Flask 2 from flask_compress import Compress 3 4 compress = Compress() 5 6 def start_app(): 7 app = Flask(__name__) 8 compress.init_app(app) 9 return app
5、選項
Within your Flask application‘s settings you can provide the following settings to control the behavior of Flask-Compress. None of the settings are required.
Option | Description | Default |
---|---|---|
COMPRESS_MIMETYPES |
Set the list of mimetypes to compress here. | [ ‘text/html‘, ‘text/css‘, ‘text/xml‘, ‘application/json‘, ‘application/javascript‘ ] |
COMPRESS_LEVEL |
Specifies the gzip compression level. | 6 |
COMPRESS_MIN_SIZE |
Specifies the minimum file size threshold for compressing files. | 500 |
COMPRESS_CACHE_KEY |
Specifies the cache key method for lookup/storage of response data. | None |
COMPRESS_CACHE_BACKEND |
Specified the backend for storing the cached response data. | None |
COMPRESS_REGISTER |
Specifies if compression should be automatically registered. |
|
6、示例:
7、說下http頭Vary的作用:指定Vary: Accept-Encoding標頭可告訴代理服務器緩存兩種版本的資源:壓縮和非壓縮,這有助於避免一些公共代理不能正確地檢測Content-Encoding標頭的問題
參考:1、http://blog.csdn.net/fupengyao/article/details/50915526
2、http://www.webkaka.com/blog/archives/how-to-set-Vary-Accept-Encoding-header.html
8、nginx配置gzip壓縮
默認情況下,Nginx的gzip壓縮是關閉的,也只對只對text/html進行壓縮,需要在編輯nginx.conf文件,在http段加入一下配置,常用配置片段如下:
gzip on;
gzip_comp_level 6; # 壓縮比例,比例越大,壓縮時間越長。默認是1
gzip_types text/xml text/plain text/css application/javascript
application/x-javascript application/rss+xml; # 哪些文件可以被壓縮
gzip_disable "MSIE [1-6]\."; # IE6無效
9、http的vary頭在nginx中的配置方法
gzip_vary on
flask-compress的使用方法