Skip to content

Instantly share code, notes, and snippets.

@RedCraig
Created July 29, 2015 22:37
Show Gist options
  • Save RedCraig/94e43cdfe447964812c3 to your computer and use it in GitHub Desktop.
Save RedCraig/94e43cdfe447964812c3 to your computer and use it in GitHub Desktop.
Gzip for particular views (Flask snippet updated to Python3)
"""
Compress results using a decorator. From:
http://flask.pocoo.org/snippets/122/
updated to use python3
"""
from flask import after_this_request, request
import gzip
import functools
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
response.data = gzip.compress(response.data)
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
@mik-laj
Copy link

mik-laj commented Jun 14, 2020

Small optimization:

"""
Compress results using a decorator. From:
http://flask.pocoo.org/snippets/122/
updated to use python3
"""

from flask import after_this_request, request
import gzip
import functools


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

            compressed_data = gzip.compress(response.data)
            if len(compressed_data) < len(response.data):
                response.data = compressed_data
                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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment