Skip to content

Commit

Permalink
Added middleware for Django developer toolbar to be print JSON as HTM…
Browse files Browse the repository at this point in the history
…L, which enables the toolbar for API calls. Append an empty query parameter to an API call like so: http://192.168.50.50:8000/api/v1/data_sets/?format=json&debug
  • Loading branch information
flekschas committed Jun 25, 2015
1 parent 0c44885 commit b57277e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
33 changes: 33 additions & 0 deletions refinery/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class JsonAsHTML(object):
"""
View a JSON response in your browser as HTML if the request has a `debug`
query parameter
E.g. http://192.168.50.50:8000/api/v1/data_sets/?format=json&debug
Useful for viewing stats using Django Debug Toolbar
This middleware should be place AFTER Django Debug Toolbar middleware
"""

def process_response(self, request, response):

# not for production or production like environment
if request.GET.get('debug') != '':
return response

# do nothing for actual ajax requests
if request.is_ajax():
return response

# only do something if this is a json response
if "application/json" in response['Content-Type'].lower():
title = "JSON as HTML Middleware for: %s" % request.get_full_path()
response.content = (
"<html><head><title>{title}</title></head><body><pre>{body}"
"</pre></body></html>".format(
title=title,
body=response.content
)
)
response['Content-Type'] = 'text/html'
return response
3 changes: 2 additions & 1 deletion refinery/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,8 +214,9 @@ def get_setting(name, settings=local_settings):
)
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
'middleware.JsonAsHTML',
)
INTERNAL_IPS = ('192.168.50.1' )
INTERNAL_IPS = ('192.168.50.1')


# NG: added for django-guardian
Expand Down

3 comments on commit b57277e

@hackdna
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are web browsers plugins like Postman that address this on the client side.

@flekschas
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please show us how to enable the Django debug toolbar with Postman.

@hackdna
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, I was thinking of just the problem of formatting JSON output. Still, a better solution might be to create a simple Tastypie HTML serializer to avoid overhead of middleware which may be relevant for performance profiling.

Please sign in to comment.