Skip to content

Commit

Permalink
Support gzip response (#154)
Browse files Browse the repository at this point in the history
* add gzip compress and decompress

* support gzip response
  • Loading branch information
zaw007 authored Aug 14, 2020
1 parent 3929742 commit 83d398d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 7 additions & 2 deletions flask_debugtoolbar/__init__.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 83d398d

Please sign in to comment.