如何使用django-debug-toolbar for django-tastypie?

eug*_*ene 23 django debugging tastypie

django-debug-toolbar需要输出为html,但django-tastypie的默认输出格式是json.

我试过发送,http://localhost/api/v1/resource/?format=html但它说Sorry, not implemented yet. Please append "?format=json" to your URL

即使这个文档列出了html作为有效选项之一,它也说明了它TODO list.
http://django-tastypie.readthedocs.org/en/latest/serialization.html#to-html

如何使用调试工具栏来调试tastypie api调用?
(例如,我想看看为api调用运行了多少个sql查询..等等)

也许我可以从django视图中调用api但是如何?

Ben*_*sty 36

这是我为类似目的编写的中间件,它在HTML中包装json以启用调试工具栏并且还可以打印它.此外,它支持二进制数据.我没有使用tastypie,但我认为它也应该适用.

# 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
Run Code Online (Sandbox Code Playgroud)

  • 次要修复:这对我来说不适用于Django 1.7的回答.我不得不改变MIDDLEWARE_CLASSES包括:而不是'NonHtmlDebugToolbarMiddleware'我必须指定'myapp.settings.NonHtmlDebugToolbarMiddleware'.除此之外 - 太棒了! (3认同)

小智 8

Django调试工具栏的中间件实际上有代码,以防止它被激活为非类型的响应,如TastyPie返回的响应.我过去所做的是创建一些中间件,将json响应转换为HTML,这样工具栏就会被激活,我可以计算查询等......这有点像黑客,但它可以完成工作并且很容易打开/关闭.

from django.conf import settings


class JsonAsHTML(object):
    '''
    View a JSON response in your browser as HTML
    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 not settings.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>%s</title></head><body>%s</body></html>" % (title, response.content)
            response['Content-Type'] = 'text/html'
        return response
Run Code Online (Sandbox Code Playgroud)