Django-debug-toolbar: Панель инструментов не отображается для запросов POST

Созданный на 4 окт. 2017  ·  6Комментарии  ·  Источник: jazzband/django-debug-toolbar

Привет, я пытаюсь отладить проблему, при которой запросы POST не вызывают отображение панели инструментов, для любого другого запроса GET панель инструментов отладки отображается нормально, похоже, не быть проблемой для других пользователей, поэтому мне интересно, не вызывает ли что-то панель инструментов, или это не поддерживаемая функция.

Это происходит только по запросу ViewSets , ModelViewSet из структуры django rest, похоже, работает нормально, как я могу понять, что не так?

Самый полезный комментарий

Вот мое промежуточное ПО для решения этой проблемы:

def Fix_XMLHttpRequest(get_response):
    def middleware(request):
        # When `POST`ing data from the DRF browsable API, it will set the
        # header `X_REQUESTED_WITH: XMLHttpRequest`. (Not sure if the browser
        # adds that header of if DRF's front-end does, but that doesn't matter,
        # the header is there.) It's a little contradictory that the header is
        # there since the browser also requests that the response be 'text/html'.
        # Anyway, that's fine except for one thing. Django Debug Toolbar will
        # not show the debug toolbar whenever that header is set on the request!
        #
        # See:
        #   - https://github.com/jazzband/django-debug-toolbar/blob/c201ce34cea3ba4ce99d1642db17f2cb31c6204e/debug_toolbar/middleware.py#L59
        #   - https://docs.djangoproject.com/en/2.1/_modules/django/http/request/#HttpRequest.is_ajax
        #
        # My workaround is to remove that header whenever the request explicitly
        # asks for 'text/html'. Again, in my opinion, that header doesn't really
        # make sense anyway when the browser wants to receive HTML back.
        #
        # This makes is so that when you POST data from the DRF browsable API,
        # you can still see the Django Debug Toolbar. It maintains the desired
        # behavior of _not_ showing the toolbar when you POST from Javascript
        # to obtain JSON data.

        if 'text/html' in request.META.get('HTTP_ACCEPT', ''):
            if request.META.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest':
                del request.META['HTTP_X_REQUESTED_WITH']

        response = get_response(request)

        return response

    return middleware

Не забудьте добавить это промежуточное программное обеспечение _ перед_ промежуточным программным обеспечением вашей панели инструментов Django Debug Toolbar.

Все 6 Комментарий

Я бы начал здесь https://github.com/jazzband/django-debug-toolbar/blob/master/debug_toolbar/middleware.py#L58 соответственно с SHOW_TOOLBAR_CALLBACK .

Я не уверен, почему запросы POST игнорируются панелью инструментов?

Вот мое промежуточное ПО для решения этой проблемы:

def Fix_XMLHttpRequest(get_response):
    def middleware(request):
        # When `POST`ing data from the DRF browsable API, it will set the
        # header `X_REQUESTED_WITH: XMLHttpRequest`. (Not sure if the browser
        # adds that header of if DRF's front-end does, but that doesn't matter,
        # the header is there.) It's a little contradictory that the header is
        # there since the browser also requests that the response be 'text/html'.
        # Anyway, that's fine except for one thing. Django Debug Toolbar will
        # not show the debug toolbar whenever that header is set on the request!
        #
        # See:
        #   - https://github.com/jazzband/django-debug-toolbar/blob/c201ce34cea3ba4ce99d1642db17f2cb31c6204e/debug_toolbar/middleware.py#L59
        #   - https://docs.djangoproject.com/en/2.1/_modules/django/http/request/#HttpRequest.is_ajax
        #
        # My workaround is to remove that header whenever the request explicitly
        # asks for 'text/html'. Again, in my opinion, that header doesn't really
        # make sense anyway when the browser wants to receive HTML back.
        #
        # This makes is so that when you POST data from the DRF browsable API,
        # you can still see the Django Debug Toolbar. It maintains the desired
        # behavior of _not_ showing the toolbar when you POST from Javascript
        # to obtain JSON data.

        if 'text/html' in request.META.get('HTTP_ACCEPT', ''):
            if request.META.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest':
                del request.META['HTTP_X_REQUESTED_WITH']

        response = get_response(request)

        return response

    return middleware

Не забудьте добавить это промежуточное программное обеспечение _ перед_ промежуточным программным обеспечением вашей панели инструментов Django Debug Toolbar.

Я не уверен, что это нормально или нет. Я пытаюсь использовать много способов для захвата почтового запроса, но все еще не могу, это означает, что если вы используете запрос на веб-сайте с методом get, очевидно, что это не проблема. Я использую Django для разработки сервера для мобильного клиента, и большая часть метода запроса - POST. Надеюсь, вы, ребята, можете мне помочь, цените.

Что сработало для меня (в сочетании с доступным для просмотра API Django REST Framework), так это django-debug-toolbar-history .

django-debug-toolbar-history также работал у меня с использованием просматриваемых страниц разработчика DRF.

Это позволило мне отслеживать запросы SQL, используемые во время POST.

Закрытие по мере освобождения панели истории. Я также подтвердил, что для запросов POST, которые возвращаются, и ответа HTML отображается панель инструментов дебюта.

Если вы обновились до последней версии и по-прежнему сталкиваетесь с ошибкой, пожалуйста, откройте страницу с новыми сведениями. Спасибо.

Была ли эта страница полезной?
0 / 5 - 0 рейтинги