Skip to content

Instantly share code, notes, and snippets.

@thebouv
Created December 30, 2019 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebouv/056cfffdf8f436227e4f187aa101c6ce to your computer and use it in GitHub Desktop.
Save thebouv/056cfffdf8f436227e4f187aa101c6ce to your computer and use it in GitHub Desktop.
python flask gzip example
import gzip, functools
from io import BytesIO as IO
from flask import after_this_request, request
def gzipped(f):
@functools.wraps(f)
def view_func(*args, **kwargs):
@after_this_request
def zipper(response):
accept_encoding = request.headers.get('Accept-Encoding', '')
if 'gzip' not in accept_encoding.lower():
return response
response.direct_passthrough = False
if (response.status_code < 200 or
response.status_code >= 300 or
'Content-Encoding' in response.headers):
return response
gzip_buffer = IO()
gzip_file = gzip.GzipFile(mode='wb',
fileobj=gzip_buffer)
gzip_file.write(response.data)
gzip_file.close()
response.data = gzip_buffer.getvalue()
response.headers['Content-Encoding'] = 'gzip'
response.headers['Vary'] = 'Accept-Encoding'
response.headers['Content-Length'] = len(response.data)
return response
return f(*args, **kwargs)
return view_func
@gzipped
def get_data():
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment