Skip to content

Instantly share code, notes, and snippets.

@juanwolf
Last active November 28, 2019 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juanwolf/033eb634d0154e0ef019d709877270d3 to your computer and use it in GitHub Desktop.
Save juanwolf/033eb634d0154e0ef019d709877270d3 to your computer and use it in GitHub Desktop.
DRF Debug JSON Format
# Code adapted for django 1.10 and python3 from https://stackoverflow.com/a/19249559/2622605
from django.http import HttpResponse
import json
class NonHtmlDebugToolbarMiddleware:
"""
The Django Debug Toolbar usually only works for views that return HTML.
This middleware wraps any non-HTML response in HTML if the request
has a 'debug' query parameter (e.g. http://localhost/foo?debug)
Special handling for json (pretty printing) and
binary data (only show data length)
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.GET.get("debug") == "":
if response['Content-Type'] == 'application/octet-stream':
new_content = '<html><body>Binary Data, ' \
'Length: {}</body></html>'.format(len(response.content))
response = HttpResponse(new_content)
elif response['Content-Type'] != 'text/html':
content = response.content
try:
json_ = json.loads(content.decode('utf8'))
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