Gzip响应是指在Web应用中,服务器对响应内容进行Gzip压缩后再发送给客户端,以减小传输数据量,提高网络传输效率。在Flask和Tornado框架中,都可以实现Gzip响应功能。
Flask本身不直接支持Gzip,但可以通过中间件或扩展实现:
from flask import Flask
from flask_compress import Compress
app = Flask(__name__)
compress = Compress()
compress.init_app(app)
@app.route('/')
def index():
return {"message": "This response will be compressed if client supports it"}
if __name__ == '__main__':
app.run()
from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.middleware.http_proxy import ProxyMiddleware
from werkzeug.middleware.shared_data import SharedDataMiddleware
from werkzeug.middleware.gzip import GzipMiddleware
app = Flask(__name__)
app.wsgi_app = GzipMiddleware(app.wsgi_app, compresslevel=6)
@app.route('/')
def index():
return "This response will be compressed"
if __name__ == '__main__':
app.run()
Tornado内置支持Gzip压缩:
import tornado.ioloop
import tornado.web
import tornado.httpserver
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("This response will be compressed if client supports it")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
], compress_response=True) # 启用Gzip压缩
if __name__ == "__main__":
app = make_app()
server = tornado.httpserver.HTTPServer(app)
server.listen(8888)
tornado.ioloop.IOLoop.current().start()
app.config['COMPRESS_REGISTER'] = True # 默认True,自动压缩响应
app.config['COMPRESS_MIMETYPES'] = [ # 默认压缩的MIME类型
'text/html',
'text/css',
'text/xml',
'application/json',
'application/javascript'
]
app.config['COMPRESS_LEVEL'] = 6 # 压缩级别,1-9
app.config['COMPRESS_MIN_SIZE'] = 500 # 最小压缩大小(字节)
settings = {
"compress_response": True, # 启用Gzip
"gzip": True, # 同compress_response
"gzip_mime_types": { # 指定压缩的MIME类型
"text/plain",
"text/html",
"text/css",
"application/x-javascript",
"text/xml",
"application/xml",
"application/xml+rss",
"text/javascript",
"application/javascript",
"application/json"
},
"gzip_min_length": 1024 # 最小压缩长度
}
可能原因:
Accept-Encoding: gzip
解决方案:
可能原因:
解决方案:
可能原因:
解决方案:
Content-Encoding
头正确设置通过合理配置Gzip响应,可以显著提升Web应用的性能表现,特别是在网络带宽有限或内容较大的情况下。
没有搜到相关的文章