Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为django tastypie使用django调试工具栏?_Django_Debugging_Tastypie - Fatal编程技术网

如何为django tastypie使用django调试工具栏?

如何为django tastypie使用django调试工具栏?,django,debugging,tastypie,Django,Debugging,Tastypie,django调试工具栏需要输出为html,但django tastypie的默认输出格式为json 我尝试发送http://localhost/api/v1/resource/?format=html但上面写着对不起,还没有实现。请在URL中附加“?format=json” 尽管此文档将html列为有效选项之一,但它会在待办事项列表中显示它的名称 如何使用调试工具栏调试tastypie api调用? (例如,我想看看有多少sql查询正在为api调用运行..等等) 也许我可以从django视图调

django调试工具栏需要输出为html,但django tastypie的默认输出格式为json

我尝试发送
http://localhost/api/v1/resource/?format=html
但上面写着
对不起,还没有实现。请在URL中附加“?format=json”

尽管此文档将html列为有效选项之一,但它会在
待办事项列表中显示它的名称

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

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

恐怕不可能。有关可行的解决方案,请参见公认的答案

以下是您的方法不起作用的原因:

工具栏不会启动,因为答案是正确的。工具栏的中间件无法“解析”所有其他格式以包含工具栏

不过,您可以添加自己的工具来显示SQL查询。看看这个简单的片段:或者你可以使用第三方应用程序,比如

例如,您可以检查
DEBUG是否为True
,并将此信息添加到tastype返回的“meta”对象中

另外,请查看控制台(runserver)中的SQL日志记录。一些有用的资源:

试试看

这将允许调试工具栏在调用页面上显示有关请求的信息

或者,如果您想要一个HTML呈现程序,并且您的项目不太深入,我强烈建议使用django rest framework

@HTML\u decorator
@html_decorator
def test(request):

    view = resolve("/api/v1/albumimage/like/user/%d/" % 2 )

    accept =  request.META.get("HTTP_ACCEPT")
    accept += ",application/json"
    request.META["HTTP_ACCEPT"] = accept   
    res = view.func(request, **view.kwargs)

    return HttpResponse(res._container)



def html_decorator(func):
    """                                                                                                                                                                                                                                                                       
    wrap it inside html                                                                                                                                                                                                                                                       
    """

    def _decorated(*args, ** kwargs):
        response = func(*args, **kwargs)

        wrapped = ("<html><body>",
                   response.content,
                   "</body></html>")

        return HttpResponse(wrapped)

    return _decorated
def测试(请求): view=resolve(“/api/v1/albumimage/like/user/%d/%2”) accept=request.META.get(“HTTP_accept”) 接受+=”,应用程序/json“ request.META[“HTTP_ACCEPT”]=ACCEPT res=view.func(请求,**view.kwargs) 返回HttpResponse(res.\u容器) def html_装饰器(func): """ 将其包装在html中 """ def_装饰(*args,**kwargs): 响应=func(*args,**kwargs) 包装=(“”, 回应.内容, "") 返回HttpResponse(已包装) 返回
我就是这样解决的。

好的,它不是自动的,但现在可以

我通过从


下面是我为类似目的编写的一个中间件,它将json封装在HTML中,以启用调试工具栏,并将其漂亮地打印出来。此外,它还支持二进制数据。我没有使用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
#设置-dev.py
从django.http导入HttpResponse
导入json
中间件\u类+=(
“调试工具条.中间件.调试工具条中间件”,
“非HTMLDEBUG中间件”,
)
类非HTMLDEBUG中间件(对象):
"""
Django调试工具栏通常仅适用于返回HTML的视图。
如果请求失败,该中间件将任何非HTML响应包装为HTML
具有“调试”查询参数(例如。http://localhost/foo?debug)
对json(漂亮打印)和
二进制数据(仅显示数据长度)
"""
@静力学方法
def过程_响应(请求、响应):
if request.GET.GET('debug')='':
如果响应['Content-Type']=='application/octet-stream':
新内容='二进制数据,'\
'长度:{}'。格式(len(response.content))
响应=HttpResponse(新内容)
elif响应['Content-Type']!='text/html':
content=response.content
尝试:
json\uux=json.loads(内容)
content=json.dumps(json\u,sort\u keys=True,indent=2)
除值错误外:
通过
response=HttpResponse(“{}”
“”.格式(内容))
返回响应

Django Debug工具栏的中间件实际上包含代码,以防止对非html类型的响应(如TastyPie返回的响应)激活它。我过去所做的是创建一个中间件,将json响应转换为HTML,这样工具栏将被激活,我可以计算查询等。。。这是一个有点黑客,但它可以完成工作,很容易打开/关闭

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
来自django.conf导入设置的

类JsonAsHTML(对象):
'''
在浏览器中以HTML格式查看JSON响应
用于使用Django调试工具栏查看统计信息
这个中间件应该放在Django调试工具栏中间件之后
'''
def过程_响应(自我、请求、响应):
#不适用于生产或类似生产的环境
如果不是settings.DEBUG:
返回响应
#对实际的ajax请求不执行任何操作
if request.is_ajax():
返回响应
#仅当这是json响应时才执行某些操作
如果响应['Content-Type']中的“application/json”。lower()
title=“JSON作为%s”%request的HTML中间件。获取完整路径()
response.content=“%s%s”%(标题,response.content)
响应['Content-Type']='text/html'
返回响应

Django 1.10引入了“新型中间件”:

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

导入json
从django.http导入HttpResponse
类非HTMLDEBUG中间件:
"""
Django调试工具栏通常仅适用于返回HTML的视图。
这个中间件包
# 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
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
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