Skip to content

Instantly share code, notes, and snippets.

@lsiden
Created June 4, 2021 15:47
Show Gist options
  • Save lsiden/c91b72e67d8150819aacf1a3993979ca to your computer and use it in GitHub Desktop.
Save lsiden/c91b72e67d8150819aacf1a3993979ca to your computer and use it in GitHub Desktop.
Decorator to gzip Respone payload
"""Decorator to gzip Respone payload
Obtained from http://kb.sites.apiit.edu.my/knowledge-base/how-to-gzip-response-in-flask/
Example use case:
@gzipped
def get_data():
return response
"""
import logging
import gzip
import functools
from flask import after_this_request, request
LOGGER = logging.getLogger(__name__)
def gzipped(func):
@functools.wraps(func)
def view_func(*args, **kwargs):
@after_this_request
def _(resp):
if cannot_zip(resp):
return resp
accept_encoding = request.headers.get('Accept-Encoding', '')
if 'gzip' not in accept_encoding.lower():
return resp
resp.direct_passthrough = False
resp.data = gzip.compress(resp.data)
resp.headers['Content-Encoding'] = 'gzip'
resp.headers['Content-Length'] = len(resp.data)
return resp
return func(*args, **kwargs)
return view_func
def cannot_zip(resp):
return (resp.status_code < 200 or
resp.status_code >= 300 or
resp.status_code == 204 or # no content
'Content-Encoding' in resp.headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment