diff --git a/flask_debugtoolbar/__init__.py b/flask_debugtoolbar/__init__.py index a761ddb..3513eab 100644 --- a/flask_debugtoolbar/__init__.py +++ b/flask_debugtoolbar/__init__.py @@ -8,7 +8,7 @@ from werkzeug.urls import url_quote_plus from flask_debugtoolbar.compat import iteritems from flask_debugtoolbar.toolbar import DebugToolbar -from flask_debugtoolbar.utils import decode_text +from flask_debugtoolbar.utils import decode_text, gzip_compress, gzip_decompress try: # Python 3.8+ @@ -210,7 +210,10 @@ class DebugToolbarExtension(object): response.headers['content-type'].startswith('text/html')): return response - response_html = response.data.decode(response.charset) + if 'gzip' in response.headers.get('Content-Encoding', ''): + response_html = gzip_decompress(response.data).decode(response.charset) + else: + response_html = response.data.decode(response.charset) no_case = response_html.lower() body_end = no_case.rfind('') @@ -235,6 +238,8 @@ class DebugToolbarExtension(object): content = ''.join((before, toolbar_html, after)) content = content.encode(response.charset) + if 'gzip' in response.headers.get('Content-Encoding', ''): + content = gzip_compress(content) response.response = [content] response.content_length = len(content) diff --git a/flask_debugtoolbar/utils.py b/flask_debugtoolbar/utils.py index 9b211f3..fc8ac70 100644 --- a/flask_debugtoolbar/utils.py +++ b/flask_debugtoolbar/utils.py @@ -1,6 +1,8 @@ import itertools import os.path import sys +import io +import gzip try: from pygments import highlight @@ -83,3 +85,14 @@ def format_sql(query, args): query, SqlLexer(), HtmlFormatter(noclasses=True, style=PYGMENT_STYLE))) + +def gzip_compress(data, compresslevel=6): + buff = io.BytesIO() + with gzip.GzipFile(fileobj=buff, mode='wb', compresslevel=compresslevel) as f: + f.write(data) + return buff.getvalue() + + +def gzip_decompress(data): + with gzip.GzipFile(fileobj=io.BytesIO(data), mode='rb') as f: + return f.read()