Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support gzip response #154

Merged
merged 2 commits into from Aug 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 7 additions & 2 deletions flask_debugtoolbar/__init__.py
Expand Up @@ -8,7 +8,7 @@

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+
Expand Down Expand Up @@ -210,7 +210,10 @@ def process_response(self, response):
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('</body>')
Expand All @@ -235,6 +238,8 @@ def process_response(self, response):

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)

Expand Down
13 changes: 13 additions & 0 deletions flask_debugtoolbar/utils.py
@@ -1,6 +1,8 @@
import itertools
import os.path
import sys
import io
import gzip

try:
from pygments import highlight
Expand Down Expand Up @@ -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()