Skip to content

Instantly share code, notes, and snippets.

@jdunck
Forked from leetrout/force_html_middleware.py
Last active August 29, 2015 14:02
Show Gist options
  • Save jdunck/5f8c516c8620d976d51a to your computer and use it in GitHub Desktop.
Save jdunck/5f8c516c8620d976d51a to your computer and use it in GitHub Desktop.
A hack to wrap API responses in HTML so that django debug toolbar can be used on API requests.
def uncompress_string(c):
from io import BytesIO
from gzip import GzipFile
zbuf = BytesIO(c)
with GzipFile(mode='rb', compresslevel=6, fileobj=zbuf) as zfile:
return zfile.read()
class ForceDebugJSONMiddleware(object):
def process_response(self, request, response):
"""Add html, head, and body tags so debug toolbar will activate."""
if not (request.GET.get('debug') and settings.DEBUG):
return response
content = response.content
was_compressed = False
if 'content-encoding' in response:
if response['Content-Encoding'] != 'gzip':
logger.warning("Unsure how to debug response on content encoding {0}".format(response['Content-Encoding']))
return response
content = uncompress_string(response.content)
was_compressed = True
if '<body>' not in content:
response.content = '<html><head></head><body>%s</body></html>' % content
response['Content-Length'] = str(len(response.content))
response['Content-Type'] = 'text/html'
if was_compressed:
del response['Content-Encoding']
if response.has_header('ETag'):
response['ETag'] = re.sub('"$', ';ungzip"', response['ETag'])
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment