Skip to content

Instantly share code, notes, and snippets.

@ulgens
Created June 12, 2018 15:41
Show Gist options
  • Save ulgens/17105a9d24ea5e49b9705035d745ff2d to your computer and use it in GitHub Desktop.
Save ulgens/17105a9d24ea5e49b9705035d745ff2d to your computer and use it in GitHub Desktop.
Profile non HTML responses with debug_toolbar
class NonHtmlDebugToolbarMiddleware(MiddlewareMixin):
"""
Converts non-HTML responses to HTML,
for being able to profile them with django debug toolbar.
Usage: /<endpoint>/?format=json&profile=1
"""
def process_response(self, request, response):
profile = request.GET.get('profile')
if not profile:
return response
# assumes response['Content-Type'] != 'text/html'
content = response.content
try:
json_ = json.loads(content)
content = json.dumps(json_, sort_keys=True, indent=2)
except ValueError:
pass
response = HttpResponse('<html><body><pre>{} </pre></body></html>'.format(content))
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment