首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用django-debug-toolbar for django-tastypie?

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

Stack Overflow用户
提问于 2013-01-31 11:57:22
回答 7查看 7.7K关注 0票数 25

django-debug-工具栏需要它的输出是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调用?

(例如,我想看看有多少sql查询正在为api调用运行。以此类推)

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

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2013-10-08 21:49:56

下面是我为类似目的编写的一个中间件,它将json包装在HTML中,以启用调试工具栏,并打印出来。此外,它还支持二进制数据。我没有使用tastypie,但我认为它也应该与它一起工作。

代码语言:javascript
复制
# 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
票数 39
EN

Stack Overflow用户

发布于 2013-11-05 05:59:01

Django Debug Toolbar的中间件实际上包含代码,以防止它被激活用于非html类型的响应,如TastyPie返回的响应。我在过去所做的是创建一些中间件来将json响应转换成HTML,这样工具栏就会被激活,我可以计算查询等。这是一个小技巧,但它可以完成工作,并且很容易打开/关闭。

代码语言:javascript
复制
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
票数 8
EN

Stack Overflow用户

发布于 2018-04-25 22:02:00

Django1.10引入了“新型中间件”:https://docs.djangoproject.com/en/2.0/releases/1.10/#new-style-middleware

这是一个新风格的中间件版本:

代码语言:javascript
复制
import json

from django.http import HttpResponse


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 response['Content-Type'] == 'application/json':
            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),
                                    content_type='text/html')

        return response
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14618203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档