class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            self.debug_toolbar.load_panels()
            debug = request.GET.get('djDebug')
            # kinda ugly, needs changes to the loader to optimize
            for panel in self.debug_toolbar.panels:
                response = panel.process_request(request)
                if not response:
                    if debug == panel.name:
                        response = panel.process_ajax(request)
                if response:
                    response.skip_debug_response = True
                    return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        if self.show_toolbar(request):
            for panel in self.debug_toolbar.panels:
                cb = panel.process_view(request, callback, callback_args, callback_kwargs)
                if cb:
                    callback = cb
            return callback

    def process_response(self, request, response):
        if self.show_toolbar(request) and not getattr(response, 'skip_debug_response', False):
            if response['Content-Type'].split(';')[0] in _HTML_TYPES and not request.is_ajax():
                # Saving this here in case we ever need to inject into <head>
                #response.content = _END_HEAD_RE.sub(smart_str(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
                for panel in self.debug_toolbar.panels:
                    nr = panel.process_response(request, response)
                    # Incase someone forgets `return response`
                    if nr: response = nr
                response.content = _END_BODY_RE.sub(smart_str('<body>' + self.debug_toolbar.render_toolbar()), response.content)
        return response
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax():
            return False
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            self.debug_toolbar.load_panels()

            # Monkeypatch in the URLpatterns for the debug toolbar. The last item
            # in the URLpatterns needs to be ```('', include(ROOT_URLCONF))``` so
            # that the existing URLs load *after* the ones we patch in. However,
            # this is difficult to get right: a previous middleware might have
            # changed request.urlconf, so we need to pick that up instead.
            original_urlconf = getattr(request, 'urlconf',
                                       settings.ROOT_URLCONF)
            debug_toolbar.urls.urlpatterns += patterns(
                '',
                ('', include(original_urlconf)),
            )
            request.urlconf = 'debug_toolbar.urls'

        return None

    def process_response(self, request, response):
        if response.status_code != 200:
            return response
        if self.show_toolbar(request):
            if response['Content-Type'].split(';')[0] in _HTML_TYPES:
                # Saving this here in case we ever need to inject into <head>
                #response.content = _END_HEAD_RE.sub(smart_str(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
                response.content = _END_BODY_RE.sub(
                    smart_str('<body\\1>' +
                              self.debug_toolbar.render_toolbar()),
                    response.content)
        return response
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax():
            return False
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            self.debug_toolbar.load_panels()
            
            # Monkeypatch in the URLpatterns for the debug toolbar. The last item
            # in the URLpatterns needs to be ```('', include(ROOT_URLCONF))``` so
            # that the existing URLs load *after* the ones we patch in. However,
            # this is difficult to get right: a previous middleware might have
            # changed request.urlconf, so we need to pick that up instead.
            original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
            debug_toolbar.urls.urlpatterns += patterns('',
                ('', include(original_urlconf)),
            )
            request.urlconf = 'debug_toolbar.urls'
            
        return None

    def process_response(self, request, response):
        if response.status_code != 200:
            return response
        if self.show_toolbar(request):
            if response['Content-Type'].split(';')[0] in _HTML_TYPES:
                # Saving this here in case we ever need to inject into <head>
                #response.content = _END_HEAD_RE.sub(smart_str(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
                response.content = _END_BODY_RE.sub(smart_str('<body\\1>' + self.debug_toolbar.render_toolbar()), response.content)
        return response
示例#4
0
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None

    def process_request(self, request):
        if settings.DEBUG:
            self.debug_toolbar = DebugToolbar()
            self.debug_toolbar.load_panels()
        return None

    def process_response(self, request, response):
        if settings.DEBUG:
            if response['Content-Type'].split(';')[0] in _HTML_TYPES:
                #response.content = _END_HEAD_RE.sub(mark_safe(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
                response.content = _END_BODY_RE.sub(mark_safe(self.debug_toolbar.render_toolbar() + '</body>'), response.content)
        return response
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None
        self.original_urlconf = settings.ROOT_URLCONF
        self.original_pattern = patterns('', ('', include(self.original_urlconf)),)
        self.override_url = True

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax():
            return False
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.override_url:
            debug_toolbar.urls.urlpatterns += self.original_pattern
            self.override_url = False
        request.urlconf = 'debug_toolbar.urls'

        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            for panel in self.debug_toolbar.panels:
                panel.process_request(request)

        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.debug_toolbar:
            for panel in self.debug_toolbar.panels:
                panel.process_view(request, view_func, view_args, view_kwargs)

    def process_response(self, request, response):
        if not self.debug_toolbar:
            return response
        if self.debug_toolbar.config['INTERCEPT_REDIRECTS']:
            if isinstance(response, HttpResponseRedirect):
                redirect_to = response.get('Location', None)
                if redirect_to:
                    response = render_to_response(
                        'debug_toolbar/redirect.html',
                        {'redirect_to': redirect_to}
                    )
        if response.status_code != 200:
            return response
        for panel in self.debug_toolbar.panels:
            panel.process_response(request, response)
        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            response.content = replace_insensitive(smart_unicode(response.content), u'</body>', smart_unicode(self.debug_toolbar.render_toolbar() + u'</body>'))
        return response
示例#6
0
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None
        self.original_urlconf = settings.ROOT_URLCONF
        self.original_pattern = patterns(
            '',
            ('', include(self.original_urlconf)),
        )
        self.override_url = True

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax():
            return False
        if settings.INTERNAL_IPS and request.META.get(
                'REMOTE_ADDR') not in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.override_url:
            debug_toolbar.urls.urlpatterns += self.original_pattern
            self.override_url = False
        request.urlconf = 'debug_toolbar.urls'

        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            for panel in self.debug_toolbar.panels:
                panel.process_request(request)

        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.debug_toolbar:
            for panel in self.debug_toolbar.panels:
                panel.process_view(request, view_func, view_args, view_kwargs)

    def process_response(self, request, response):
        if not self.debug_toolbar:
            return response
        if self.debug_toolbar.config.intercept_redirects:
            if isinstance(response, HttpResponseRedirect):
                redirect_to = response.get('Location', None)
                if redirect_to:
                    response = render_to_response(
                        'debug_toolbar/redirect.html',
                        {'redirect_to': redirect_to})
        if response.status_code != 200:
            return response
        for panel in self.debug_toolbar.panels:
            panel.process_response(request, response)
        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            if self.debug_toolbar.config.logging_enabled:
                uid = self.debug_toolbar.serialize()
                response.set_cookie('debug_toolbar_detail_url',
                                    value='http://%s:%s/__debug__/logs/%s/' %
                                    (request.META['SERVER_NAME'],
                                     request.META['SERVER_PORT'], uid))
            if self.debug_toolbar.config.toolbar_enabled:
                response.content = replace_insensitive(
                    smart_unicode(response.content), u'</body>',
                    smart_unicode(self.debug_toolbar.render_toolbar() +
                                  u'</body>'))
        return response
示例#7
0
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None

    def _show_toolbar(self, request, response=None):
        if not settings.DEBUG or not getattr(settings, 'DEBUG_TOOLBAR', True) or getattr(settings, 'TEST', False):
            return False

        if settings.MEDIA_URL and request.path.startswith(settings.MEDIA_URL):
            return False

        if response:
            if getattr(response, 'skip_debug_response', False):
                return False
            if response.status_code >= 300 and response.status_code < 400:
                return False
        
        # Allow access if remote ip is in INTERNAL_IPS or
        # the user doing the request is logged in as super user.
        if (not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 
           (not request.user.is_authenticated() or not request.user.is_superuser)):
            return False
        return True

    def static_serve(self, request, fname):
        return serve(request, fname, os.path.join(os.path.dirname(__file__), 'media'))
        
    def process_request(self, request):
        reset_tracking()
        if self._show_toolbar(request):
            if request.GET.get('djDebugStatic'):
                return self.static_serve(request, request.GET['djDebugStatic'])
            
            # Enable statistics tracking
            if not request.is_ajax():
                enable_tracking(True)
            
            self.debug_toolbar = DebugToolbar(request)
            self.debug_toolbar.load_panels()
            debug = request.GET.get('djDebug')
            
            # kinda ugly, needs changes to the loader to optimize
            response = None
            for panel in self.debug_toolbar.panels:
                if debug == panel.name:
                    response = panel.process_ajax(request)
                if not response and not request.is_ajax():
                    response = panel.process_request(request)
                if response:
                    response.skip_debug_response = True
                    return response

    def process_view(self, request, callback, callback_args, callback_kwargs):
        # TODO: this doesn't handle multiples yet
        if not request.is_ajax() and self._show_toolbar(request):
            new_callback = None
            for panel in self.debug_toolbar.panels:
                response = panel.process_view(request, callback, callback_args, callback_kwargs)
                if response:
                    return response

    def process_response(self, request, response):
        if not request.is_ajax() and self._show_toolbar(request, response):
            freeze_tracking()
            if response['Content-Type'].split(';')[0] in _HTML_TYPES:
                # Saving this here in case we ever need to inject into <head>
                #response.content = _END_HEAD_RE.sub(smart_str(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
                for panel in self.debug_toolbar.panels:
                    nr = panel.process_response(request, response)
                    # Incase someone forgets `return response`
                    if nr: response = nr
                response.content = replace_insensitive(smart_unicode(response.content), u'</body>', smart_unicode(self.debug_toolbar.render_toolbar()) + u'</body>')
        return response
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None
        self.original_urlconf = settings.ROOT_URLCONF
        self.original_pattern = patterns('', ('', include(self.original_urlconf)),)
        self.override_url = True

        # Set method to use to decide to show toolbar
        self.show_toolbar = self._show_toolbar # default
        if hasattr(settings, 'DEBUG_TOOLBAR_CONFIG'):
            show_toolbar_callback = settings.DEBUG_TOOLBAR_CONFIG.get(
                'SHOW_TOOLBAR_CALLBACK', None)
            if show_toolbar_callback:
                self.show_toolbar = show_toolbar_callback

    def _show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax() and not \
            request.path.startswith(os.path.join('/', debug_toolbar.urls._PREFIX)):
            # Allow ajax requests from the debug toolbar
            return False 
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.show_toolbar(request):
            if self.override_url:
                debug_toolbar.urls.urlpatterns += self.original_pattern
                self.override_url = False
            request.urlconf = 'debug_toolbar.urls'

            self.debug_toolbar = DebugToolbar(request)
            for panel in self.debug_toolbar.panels:
                panel.process_request(request)
        elif self.debug_toolbar:
            self.debug_toolbar = None
        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.debug_toolbar:
            for panel in self.debug_toolbar.panels:
                panel.process_view(request, view_func, view_args, view_kwargs)

    def process_response(self, request, response):
        if not self.debug_toolbar:
            return response
        if self.debug_toolbar.config['INTERCEPT_REDIRECTS']:
            if isinstance(response, HttpResponseRedirect):
                redirect_to = response.get('Location', None)
                if redirect_to:
                    response = render_to_response(
                        'debug_toolbar/redirect.html',
                        {'redirect_to': redirect_to}
                    )
        if response.status_code != 200:
            return response
        for panel in self.debug_toolbar.panels:
            panel.process_response(request, response)
        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            response.content = replace_insensitive(smart_unicode(response.content), u'</body>', smart_unicode(self.debug_toolbar.render_toolbar() + u'</body>'))
        return response
示例#9
0
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None
        self.original_urlconf = settings.ROOT_URLCONF
        self.original_pattern = patterns(
            '',
            ('', include(self.original_urlconf)),
        )
        self.override_url = True

        # Set method to use to decide to show toolbar
        self.show_toolbar = self._show_toolbar  # default
        if hasattr(settings, 'DEBUG_TOOLBAR_CONFIG'):
            show_toolbar_callback = settings.DEBUG_TOOLBAR_CONFIG.get(
                'SHOW_TOOLBAR_CALLBACK', None)
            if show_toolbar_callback:
                self.show_toolbar = show_toolbar_callback

    def _show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax() and not \
            request.path.startswith(os.path.join('/', debug_toolbar.urls._PREFIX)):
            # Allow ajax requests from the debug toolbar
            return False
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.show_toolbar(request):
            if self.override_url:
                debug_toolbar.urls.urlpatterns += self.original_pattern
                self.override_url = False
            request.urlconf = 'debug_toolbar.urls'

            self.debug_toolbar = DebugToolbar(request)
            for panel in self.debug_toolbar.panels:
                panel.process_request(request)

        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.debug_toolbar:
            for panel in self.debug_toolbar.panels:
                panel.process_view(request, view_func, view_args, view_kwargs)

    def process_response(self, request, response):
        if not self.debug_toolbar:
            return response
        if self.debug_toolbar.config['INTERCEPT_REDIRECTS']:
            if isinstance(response, HttpResponseRedirect):
                redirect_to = response.get('Location', None)
                if redirect_to:
                    response = render_to_response(
                        'debug_toolbar/redirect.html',
                        {'redirect_to': redirect_to})
        if response.status_code != 200:
            return response
        for panel in self.debug_toolbar.panels:
            panel.process_response(request, response)
        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            response.content = replace_insensitive(
                smart_unicode(response.content), u'</body>',
                smart_unicode(self.debug_toolbar.render_toolbar() +
                              u'</body>'))
        return response
示例#10
0
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax():
            return False
        if not request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        # Monkeypatch in the URLpatterns for the debug toolbar. The last item
        # in the URLpatterns needs to be ```('', include(ROOT_URLCONF))``` so
        # that the existing URLs load *after* the ones we patch in. However,
        # this is difficult to get right: a previous middleware might have
        # changed request.urlconf, so we need to pick that up instead.
        original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        debug_toolbar.urls.urlpatterns += patterns('',
            ('', include(original_urlconf)),
        )
        request.urlconf = 'debug_toolbar.urls'

        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            for panel in self.debug_toolbar.panels:
                panel.process_request(request)

        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.debug_toolbar:
            for panel in self.debug_toolbar.panels:
                panel.process_view(request, view_func, view_args, view_kwargs)

    def process_response(self, request, response):
        if not self.debug_toolbar:
            return response
        if self.debug_toolbar.config['INTERCEPT_REDIRECTS']:
            if isinstance(response, HttpResponseRedirect):
                redirect_to = response.get('Location', None)
                if redirect_to:
                    response = render_to_response(
                        'debug_toolbar/redirect.html',
                        {'redirect_to': redirect_to}
                    )
        if response.status_code != 200:
            return response
        for panel in self.debug_toolbar.panels:
            panel.process_response(request, response)
        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            # Saving this here in case we ever need to inject into <head>
            #response.content = _END_HEAD_RE.sub(smart_str(self.debug_toolbar.render_styles() + "%s" % match.group()), response.content)
            response.content = _START_BODY_RE.sub(smart_str('<body\\1>' + self.debug_toolbar.render_toolbar()), response.content)
            response.content = _END_BODY_RE.sub(smart_str('<script src="' + request.META.get('SCRIPT_NAME', '') + '/__debug__/m/toolbar.js" type="text/javascript" charset="utf-8"></script></body>'), response.content)
        return response
示例#11
0
class DebugToolbarMiddleware(object):
    """
    Middleware to set up Debug Toolbar on incoming request and render toolbar
    on outgoing response.
    """
    def __init__(self):
        self.debug_toolbar = None
        self.original_urlconf = settings.ROOT_URLCONF
        self.original_pattern = patterns('', ('', include(self.original_urlconf)),)
        self.override_url = True

    def show_toolbar(self, request):
        if not settings.DEBUG:
            return False
        if request.is_ajax():
            return False
        if settings.INTERNAL_IPS and request.META.get('REMOTE_ADDR') not in settings.INTERNAL_IPS:
            return False
        return True

    def process_request(self, request):
        if self.override_url:
            debug_toolbar.urls.urlpatterns += self.original_pattern
            self.override_url = False
        request.urlconf = 'debug_toolbar.urls'

        if self.show_toolbar(request):
            self.debug_toolbar = DebugToolbar(request)
            for panel in self.debug_toolbar.panels:
                panel.process_request(request)

        return None

    def process_view(self, request, view_func, view_args, view_kwargs):
        if self.debug_toolbar:
            for panel in self.debug_toolbar.panels:
                panel.process_view(request, view_func, view_args, view_kwargs)

    def process_response(self, request, response):
        if not self.debug_toolbar:
            return response
        if self.debug_toolbar.config.intercept_redirects:
            if isinstance(response, HttpResponseRedirect):
                redirect_to = response.get('Location', None)
                if redirect_to:
                    response = render_to_response(
                        'debug_toolbar/redirect.html',
                        {'redirect_to': redirect_to}
                    )
        if response.status_code != 200:
            return response
        for panel in self.debug_toolbar.panels:
            panel.process_response(request, response)
        if response['Content-Type'].split(';')[0] in _HTML_TYPES:
            if self.debug_toolbar.config.logging_enabled:
                uid = self.debug_toolbar.serialize()
                response.set_cookie('debug_toolbar_detail_url', value='http://%s:%s/__debug__/logs/%s/' % (request.META['SERVER_NAME'], request.META['SERVER_PORT'], uid))
            if self.debug_toolbar.config.toolbar_enabled:
                response.content = replace_insensitive(smart_unicode(response.content), u'</body>', smart_unicode(self.debug_toolbar.render_toolbar() + u'</body>'))
        return response