Compress responses with gzip.
This commit is contained in:
parent
394fc0852a
commit
c37cd60d4d
1 changed files with 33 additions and 0 deletions
|
@ -3,6 +3,8 @@ Do not execute this file directly.
|
|||
Use ycdl_launch.py to start the server with gevent.
|
||||
'''
|
||||
import flask; from flask import request
|
||||
import gzip
|
||||
import io
|
||||
import mimetypes
|
||||
import os
|
||||
import threading
|
||||
|
@ -37,6 +39,37 @@ site.jinja_env.add_extension('jinja2.ext.do')
|
|||
site.jinja_env.filters['seconds_to_hms'] = jinja_filters.seconds_to_hms
|
||||
site.debug = True
|
||||
|
||||
gzip_minimum_size = 500
|
||||
gzip_level = 3
|
||||
@site.after_request
|
||||
def after_request(response):
|
||||
'''
|
||||
Thank you close.io.
|
||||
https://github.com/closeio/Flask-gzip
|
||||
'''
|
||||
accept_encoding = request.headers.get('Accept-Encoding', '')
|
||||
|
||||
bail = False
|
||||
bail = bail or response.status_code < 200
|
||||
bail = bail or response.status_code >= 300
|
||||
bail = bail or response.direct_passthrough
|
||||
bail = bail or len(response.get_data()) < gzip_minimum_size
|
||||
bail = bail or 'gzip' not in accept_encoding.lower()
|
||||
bail = bail or 'Content-Encoding' in response.headers
|
||||
|
||||
if bail:
|
||||
return response
|
||||
|
||||
gzip_buffer = io.BytesIO()
|
||||
gzip_file = gzip.GzipFile(mode='wb', compresslevel=gzip_level, fileobj=gzip_buffer)
|
||||
gzip_file.write(response.get_data())
|
||||
gzip_file.close()
|
||||
response.set_data(gzip_buffer.getvalue())
|
||||
response.headers['Content-Encoding'] = 'gzip'
|
||||
response.headers['Content-Length'] = len(response.get_data())
|
||||
|
||||
return response
|
||||
|
||||
####################################################################################################
|
||||
####################################################################################################
|
||||
####################################################################################################
|
||||
|
|
Loading…
Reference in a new issue