Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django-debug-toolbar for django-tastypie?

Tags:

django-debug-toolbar needs its output to be html, but django-tastypie's default output format is json.

I tried sending http://localhost/api/v1/resource/?format=html but it says Sorry, not implemented yet. Please append "?format=json" to your URL

Even though this doc lists html as one of valid option, it says its on the TODO list.
http://django-tastypie.readthedocs.org/en/latest/serialization.html#to-html

How do I use debug toolbar to debug tastypie api calls?
(eg, I'd like to see how many sql queries are being run for api calls.. and so on)

Maybe I can call the api from django views but how?

like image 569
eugene Avatar asked Jan 31 '13 03:01

eugene


1 Answers

Here is a middleware I wrote for similar purposes that wraps json in HTML for enabling the debug toolbar and also pretty prints it. Furthermore, it supports binary data. I'm not using tastypie, but I think it should work with that too.

# settings-dev.py from django.http import HttpResponse import json     MIDDLEWARE_CLASSES += (     'debug_toolbar.middleware.DebugToolbarMiddleware',     'NonHtmlDebugToolbarMiddleware', )  class NonHtmlDebugToolbarMiddleware(object):     """     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)     """      @staticmethod     def process_response(request, response):         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)                     content = json.dumps(json_, sort_keys=True, indent=2)                 except ValueError:                     pass                 response = HttpResponse('<html><body><pre>{}'                                         '</pre></body></html>'.format(content))          return response 
like image 183
Benjamin Wasty Avatar answered Sep 20 '22 12:09

Benjamin Wasty