From f64026879369ce7a9c0ee3b058562eec18580650 Mon Sep 17 00:00:00 2001 From: Ethan Dalool Date: Fri, 11 Sep 2020 23:12:37 -0700 Subject: [PATCH] Gzip responses. --- frontends/etiquette_flask/backend/common.py | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/frontends/etiquette_flask/backend/common.py b/frontends/etiquette_flask/backend/common.py index b147220..2811b0a 100644 --- a/frontends/etiquette_flask/backend/common.py +++ b/frontends/etiquette_flask/backend/common.py @@ -1,4 +1,6 @@ import flask; from flask import request +import gzip +import io import mimetypes import traceback @@ -43,6 +45,37 @@ file_cache_manager = caching.FileCacheManager( max_age=BROWSER_CACHE_DURATION, ) +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 + def P_wrapper(function): def P_wrapped(thingid, response_type): if response_type not in {'html', 'json'}: