Exemple #1
0
def request_view(request):
    history = find_request_history(request)

    try:
        last_request_pair = history.last(1)[0]
    except IndexError:
        last_request_pair = None
        last_request_id = None
    else:
        last_request_id = last_request_pair[0]

    request_id = request.matchdict.get('request_id', last_request_id)
    toolbar = history.get(request_id, None)

    static_path = request.static_url(STATIC_PATH)
    root_path = request.route_url(ROOT_ROUTE_NAME)

    button_style = get_setting(request.registry.settings, 'button_style')
    max_visible_requests = get_setting(request.registry.settings,
                                       'max_visible_requests')
    hist_toolbars = history.last(max_visible_requests)
    return {
        'panels': toolbar.panels if toolbar else [],
        'static_path': static_path,
        'root_path': root_path,
        'button_style': button_style,
        'history': hist_toolbars,
        'global_panels': toolbar.global_panels if toolbar else [],
        'request_id': request_id
    }
Exemple #2
0
def request_view(request):
    history = find_request_history(request)

    try:
        last_request_pair = history.last(1)[0]
    except IndexError:
        last_request_pair = None
        last_request_id = None
    else:
        last_request_id = last_request_pair[0]

    request_id = request.matchdict.get('request_id', last_request_id)
    toolbar = history.get(request_id, None)

    static_path = request.static_url(STATIC_PATH)
    root_path = request.route_url(ROOT_ROUTE_NAME)
    
    button_style = get_setting(request.registry.settings,
            'button_style')
    max_visible_requests = get_setting(request.registry.settings, 
            'max_visible_requests')
    hist_toolbars = history.last(max_visible_requests)
    return {'panels': toolbar.panels if toolbar else [],
            'static_path': static_path,
            'root_path': root_path,
            'button_style': button_style,
            'history': hist_toolbars,
            'default_active_panels': (
                toolbar.default_active_panels if toolbar else []),
            'global_panels': toolbar.global_panels if toolbar else [],
            'request_id': request_id
            }
Exemple #3
0
 def wrapper(context, request):
     hosts = get_setting(request.registry.settings, 'hosts')
     if request.remote_addr is not None:
         last_proxy_addr = last_proxy(request.remote_addr)
         if addr_in(last_proxy_addr, hosts):
             return wrapped(context, request)
     raise HTTPNotFound('untrusted client ip address')
Exemple #4
0
def sse(request):
    response = request.response
    response.content_type = 'text/event-stream'
    history = request.pdtb_history
    response.text = U_BLANK

    active_request_id = text_(request.GET.get('request_id'))
    client_last_request_id = text_(request.headers.get('Last-Event-Id', 0))

    max_visible_requests = get_setting(request.registry.settings,
                                       'max_visible_requests')
    if history:
        last_request_pair = history.last(1)[0]
        last_request_id = last_request_pair[0]
        if not last_request_id == client_last_request_id:
            data = [
                [
                    _id,
                    toolbar.json,
                    'active' if active_request_id == _id else ''
                ]
                for _id, toolbar in history.last(max_visible_requests)
                if toolbar.visible
            ]
            if data:
                response.text = U_SSE_PAYLOAD.format(last_request_id,
                                                     json.dumps(data))
    return response
Exemple #5
0
 def wrapper(context, request):
     hosts = get_setting(request.registry.settings, 'hosts')
     if request.remote_addr is not None:
         last_proxy_addr = last_proxy(request.remote_addr)
         if addr_in(last_proxy_addr, hosts):
             return wrapped(context, request)
     raise HTTPNotFound('untrusted client ip address')
Exemple #6
0
    def process_response(self, response):
        # If the body is HTML, then we add the toolbar to the response.
        request = self.request

        if isinstance(response, WSGIHTTPException):
            # the body of a WSGIHTTPException needs to be "prepared"
            response.prepare(request.environ)

        for panel in self.panels:
            panel.process_response(response)

        if response.content_type in self.html_types:
            static_path = request.static_url(STATIC_PATH)
            root_path = request.route_url(ROOT_ROUTE_NAME)
            button_style = get_setting(request.registry.settings,
                                       'button_style', '')
            vars = {
                'panels': self.panels,
                'static_path': static_path,
                'root_path': root_path,
                'button_style': button_style
            }
            toolbar_html = render(
                'pyramid_debugtoolbar:templates/toolbar.mako',
                vars,
                request=request)
            response_html = response.body
            toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
            body = replace_insensitive(response_html, bytes_('</body>'),
                                       toolbar_html + bytes_('</body>'))
            response.app_iter = [body]
    def process_response(self, response):
        # If the body is HTML, then we add the toolbar to the response.
        request = self.request

        if isinstance(response, WSGIHTTPException):
            # the body of a WSGIHTTPException needs to be "prepared"
            response.prepare(request.environ)

        for panel in self.panels:
            panel.process_response(response)

        if response.content_type in self.html_types:
            static_path = request.static_url(STATIC_PATH)
            root_path = request.route_url(ROOT_ROUTE_NAME)
            button_style = get_setting(request.registry.settings,
                    'button_style', '')
            vars = {'panels': self.panels, 'static_path': static_path,
                    'root_path': root_path, 'button_style': button_style}
            toolbar_html = render(
                    'pyramid_debugtoolbar:templates/toolbar.dbtmako',
                    vars, request=request)
            response_html = response.body
            toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
            body = replace_insensitive(
                response_html, bytes_('</body>'),
                toolbar_html + bytes_('</body>')
                )
            response.app_iter = [body]
            response.content_length = len(body)
Exemple #8
0
def request_view(request):
    history = find_request_history(request)

    try:
        last_request_pair = history.last(1)[0]
    except IndexError:
        last_request_pair = None
        last_request_id = None
    else:
        last_request_id = last_request_pair[0]

    request_id = request.matchdict.get('request_id', last_request_id)
    toolbar = history.get(request_id, None)

    if not toolbar:
        raise NotFound

    static_path = request.static_url(STATIC_PATH)
    root_path = request.route_url(ROOT_ROUTE_NAME)
    button_style = get_setting(request.registry.settings,
            'button_style', '')
    hist_toolbars = history.last(10)
    return {'panels': toolbar.panels, 'static_path': static_path,
            'root_path': root_path, 'button_style': button_style,
            'history': hist_toolbars, 'global_panels': toolbar.global_panels,
            'request_id': request_id
            }
Exemple #9
0
def valid_host(info, request):
    hosts = get_setting(request.registry.settings, 'hosts')
    remote_addr = request.remote_addr
    if remote_addr is None:
        return False

    return addr_in(request.remote_addr, hosts)
Exemple #10
0
def valid_host(info, request):
    hosts = get_setting(request.registry.settings, 'hosts')
    remote_addr = request.remote_addr
    if remote_addr is None:
        return False

    return addr_in(request.remote_addr, hosts)
Exemple #11
0
def valid_host(info, request):
    hosts = get_setting(request.registry.settings, 'hosts')
    if request.remote_addr is None:
        return False

    last_proxy_addr = last_proxy(request.remote_addr)

    return addr_in(last_proxy_addr, hosts)
Exemple #12
0
def valid_host(info, request):
    hosts = get_setting(request.registry.settings, 'hosts')
    if request.remote_addr is None:
        return False

    last_proxy_addr = last_proxy(request.remote_addr)

    return addr_in(last_proxy_addr, hosts)
Exemple #13
0
def request_view(request):
    history = request.pdtb_history

    try:
        last_request_pair = history.last(1)[0]
    except IndexError:
        last_request_pair = None
        last_request_id = None
    else:
        last_request_id = last_request_pair[0]

    request_id = request.matchdict.get('request_id', last_request_id)
    toolbar = history.get(request_id, None)

    # set a dictionary of panels that can be accessed inside
    # DebugPanel.render_content()
    if toolbar:
        request.toolbar_panels = {
            panel.name: panel for panel in toolbar.panels
        }

    static_path = request.static_url(STATIC_PATH)
    root_path = request.route_url(ROOT_ROUTE_NAME)

    button_style = get_setting(request.registry.settings, 'button_style')
    max_visible_requests = get_setting(
        request.registry.settings, 'max_visible_requests'
    )
    hist_toolbars = history.last(max_visible_requests)
    return {
        'panels': toolbar.panels if toolbar else [],
        'static_path': static_path,
        'root_path': root_path,
        'button_style': button_style,
        'history': hist_toolbars,
        'default_active_panels': (
            toolbar.default_active_panels if toolbar else []
        ),
        'global_panels': toolbar.global_panels if toolbar else [],
        'request_id': request_id,
    }
def request_view(request):
    history = request.pdtb_history

    try:
        last_request_pair = history.last(1)[0]
    except IndexError:
        last_request_pair = None
        last_request_id = None
    else:
        last_request_id = last_request_pair[0]

    request_id = request.matchdict.get('request_id', last_request_id)
    toolbar = history.get(request_id, None)

    # set a dictionary of panels that can be accessed inside
    # DebugPanel.render_content()
    if toolbar:
        request.toolbar_panels = {
            panel.name: panel
            for panel in toolbar.panels
        }

    static_path = request.static_url(STATIC_PATH)
    root_path = request.route_url(ROOT_ROUTE_NAME)

    button_style = get_setting(request.registry.settings, 'button_style')
    max_visible_requests = get_setting(request.registry.settings,
                                       'max_visible_requests')
    hist_toolbars = history.last(max_visible_requests)
    return {'panels': toolbar.panels if toolbar else [],
            'static_path': static_path,
            'root_path': root_path,
            'button_style': button_style,
            'history': hist_toolbars,
            'default_active_panels': (
                toolbar.default_active_panels if toolbar else []),
            'global_panels': toolbar.global_panels if toolbar else [],
            'request_id': request_id
            }
 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings, "button_style", "")
     css_path = request.static_url(STATIC_PATH + "css/toolbar.css")
     toolbar_html = toolbar_html_template % {
         "button_style": button_style,
         "css_path": css_path,
         "toolbar_url": toolbar_url,
     }
     toolbar_html = toolbar_html.encode(response.charset or "utf-8")
     response.body = replace_insensitive(response_html, bytes_("</body>"), toolbar_html + bytes_("</body>"))
Exemple #16
0
 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings, 'button_style',
                                '')
     css_path = request.static_url(STATIC_PATH + 'css/toolbar_button.css')
     toolbar_html = toolbar_html_template % {
         'button_style': button_style,
         'css_path': css_path,
         'toolbar_url': toolbar_url
     }
     toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
     response.body = replace_insensitive(response_html, bytes_('</body>'),
                                         toolbar_html + bytes_('</body>'))
Exemple #17
0
 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings,
             'button_style', '')
     css_path = request.static_url(STATIC_PATH + 'css/toolbar_button.css')
     toolbar_html = toolbar_html_template % {
         'button_style': button_style,
         'css_path': css_path,
         'toolbar_url': toolbar_url}
     toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
     response.body = replace_insensitive(
         response_html, bytes_('</body>'),
         toolbar_html + bytes_('</body>')
         )
def toolbar_tween_factory(handler, registry, _logger=None):
    """ Pyramid tween factory for the debug toolbar """
    # _logger passed for testing purposes only
    if _logger is None:
        _logger = logger
    settings = registry.settings

    if not get_setting(settings, "enabled"):
        return handler

    request_history = ToolbarStorage(100)
    registry.request_history = request_history

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, "panels", [])
    global_panel_classes = get_setting(settings, "global_panels", [])
    intercept_exc = get_setting(settings, "intercept_exc")
    intercept_redirects = get_setting(settings, "intercept_redirects")
    show_on_exc_only = get_setting(settings, "show_on_exc_only")
    hosts = get_setting(settings, "hosts")
    auth_check = registry.queryUtility(IRequestAuthorization)
    exclude_prefixes = get_setting(settings, "exclude_prefixes", [])
    registry.exc_history = exc_history = None
    registry.pdtb_token = hexlify(os.urandom(10))

    if intercept_exc:
        registry.exc_history = exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == "debug"

    def toolbar_tween(request):
        request.exc_history = exc_history
        request.history = request_history
        root_url = request.route_path("debugtoolbar", subpath="")
        exclude = [root_url] + exclude_prefixes
        last_proxy_addr = None

        try:
            p = request.path
        except UnicodeDecodeError as e:
            raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason)
        starts_with_excluded = list(filter(None, map(p.startswith, exclude)))

        if request.remote_addr:
            last_proxy_addr = last_proxy(request.remote_addr)

        if (
            last_proxy_addr is None
            or starts_with_excluded
            or not addr_in(last_proxy_addr, hosts)
            or auth_check
            and not auth_check(request)
        ):
            return handler(request)

        toolbar = DebugToolbar(request, panel_classes, global_panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        # XXX
        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
            toolbar.status_int = response.status_int
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(), skip=1, show_hidden_frames=False, ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame
                exc_history.tracebacks[tb.id] = tb
                request.pdbt_tb = tb

                qs = {"token": registry.pdtb_token, "tb": str(tb.id)}
                msg = "Exception at %s\ntraceback url: %s"
                exc_url = debug_toolbar_url(request, "exception", _query=qs)
                exc_msg = msg % (request.url, exc_url)
                _logger.exception(exc_msg)

                subenviron = request.environ.copy()
                del subenviron["PATH_INFO"]
                del subenviron["QUERY_STRING"]
                subrequest = type(request).blank(exc_url, subenviron)
                response = request.invoke_subrequest(subrequest)

                toolbar.process_response(request, response)

                request.id = hexlify(id(request))
                toolbar.response = response
                toolbar.status_int = response.status_int

                request_history.put(request.id, toolbar)
                toolbar.inject(request, response)
                return response
            else:
                _logger.exception("Exception at %s" % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            "pyramid_debugtoolbar:templates/redirect.dbtmako",
                            {"redirect_to": redirect_to, "redirect_code": redirect_code},
                            request=request,
                        )
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            toolbar.process_response(request, response)
            request.id = hexlify(id(request))
            # Don't store the favicon.ico request
            # it's requested by the browser automatically
            if not "/favicon.ico" == request.path:
                toolbar.response = response
                request_history.put(request.id, toolbar)

            if not show_on_exc_only and response.content_type in html_types:
                toolbar.inject(request, response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
Exemple #19
0
def toolbar_tween_factory(handler, registry, _logger=None):
    """ Pyramid tween factory for the debug toolbar """
    # _logger passed for testing purposes only
    if _logger is None:
        _logger = logger
    settings = registry.settings

    if not get_setting(settings, 'enabled'):
        return handler

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, 'panels', [])
    intercept_exc = get_setting(settings, 'intercept_exc')
    intercept_redirects = get_setting(settings, 'intercept_redirects')
    show_on_exc_only = get_setting(settings, 'show_on_exc_only')
    hosts = get_setting(settings, 'hosts')
    auth_check = registry.queryUtility(IRequestAuthorization)
    exclude_prefixes = get_setting(settings, 'exclude_prefixes', [])
    exc_history = None

    if intercept_exc:
        exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == 'debug'

    def toolbar_tween(request):
        root_path = request.route_path(ROOT_ROUTE_NAME)
        exclude = [root_path] + exclude_prefixes
        request.exc_history = exc_history
        last_proxy_addr = None

        try:
            p = request.path
        except UnicodeDecodeError as e:
            raise URLDecodeError(e.encoding, e.object, e.start, e.end,
                                 e.reason)

        starts_with_excluded = list(filter(None, map(p.startswith, exclude)))

        if request.remote_addr:
            last_proxy_addr = last_proxy(request.remote_addr)

        if last_proxy_addr is None \
            or starts_with_excluded \
            or not addr_in(last_proxy_addr, hosts) \
            or auth_check and not auth_check(request):
            return handler(request)

        toolbar = DebugToolbar(request, panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(),
                                   skip=1,
                                   show_hidden_frames=False,
                                   ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame

                exc_history.tracebacks[tb.id] = tb
                body = tb.render_full(request).encode('utf-8', 'replace')
                response = Response(body, status=500)
                toolbar.process_response(response)
                qs = {'token': exc_history.token, 'tb': str(tb.id)}
                msg = 'Exception at %s\ntraceback url: %s'
                exc_url = request.route_url(EXC_ROUTE_NAME, _query=qs)
                exc_msg = msg % (request.url, exc_url)
                _logger.exception(exc_msg)
                return response
            else:
                _logger.exception('Exception at %s' % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            'pyramid_debugtoolbar:templates/redirect.dbtmako',
                            {
                                'redirect_to': redirect_to,
                                'redirect_code': redirect_code
                            },
                            request=request)
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            if not show_on_exc_only:
                toolbar.process_response(response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
Exemple #20
0
 def sget(opt, default=None):
     return get_setting(settings, opt, default)
def toolbar_tween_factory(handler, registry):
    """ Pyramid tween factory for the debug toolbar """
    settings = registry.settings

    if not get_setting(settings, "enabled"):
        return handler

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, "panels", [])
    intercept_exc = get_setting(settings, "intercept_exc")
    intercept_redirects = get_setting(settings, "intercept_redirects")
    hosts = get_setting(settings, "hosts")

    exc_history = None

    if intercept_exc:
        exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == "debug"

    def toolbar_tween(request):
        root_path = request.route_path(ROOT_ROUTE_NAME)
        request.exc_history = exc_history
        remote_addr = request.remote_addr

        if (remote_addr is None) or (request.path.startswith(root_path)) or (not addr_in(remote_addr, hosts)):
            return handler(request)

        toolbar = DebugToolbar(request, panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(), skip=1, show_hidden_frames=False, ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame

                exc_history.tracebacks[tb.id] = tb
                body = tb.render_full(request).encode("utf-8", "replace")
                response = Response(body, status=500)
                toolbar.process_response(response)
                qs = {"token": exc_history.token, "tb": str(tb.id)}
                msg = "Exception at %s\ntraceback url: %s"
                exc_url = request.route_path(EXC_ROUTE_NAME, _query=qs)
                exc_msg = msg % (request.url, exc_url)
                logger.exception(exc_msg)
                return response
            else:
                logger.exception("Exception at %s" % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            "pyramid_debugtoolbar:templates/redirect.dbtmako",
                            {"redirect_to": redirect_to, "redirect_code": redirect_code},
                            request=request,
                        )
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            toolbar.process_response(response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
Exemple #22
0
def toolbar_tween_factory(handler, registry):
    """ Pyramid tween factory for the debug toolbar """
    settings = registry.settings

    if not get_setting(settings, 'enabled'):
        return handler

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, 'panels', [])
    intercept_exc = get_setting(settings, 'intercept_exc')
    intercept_redirects = get_setting(settings, 'intercept_redirects')
    hosts = get_setting(settings, 'hosts')

    exc_history = None

    if intercept_exc:
        exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == 'debug'

    def toolbar_tween(request):
        root_path = request.route_path(ROOT_ROUTE_NAME)
        request.exc_history = exc_history
        remote_addr = request.remote_addr

        if (request.path.startswith(root_path) or (not remote_addr in hosts)):
            return handler(request)

        toolbar = DebugToolbar(request, panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(),
                                   skip=1,
                                   show_hidden_frames=False,
                                   ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame

                exc_history.tracebacks[tb.id] = tb
                body = tb.render_full(request).encode('utf-8', 'replace')
                response = Response(body, status=500)
                toolbar.process_response(response)
                qs = {'token': exc_history.token, 'tb': str(tb.id)}
                msg = 'Exception at %s\ntraceback url: %s'
                exc_url = request.route_url(EXC_ROUTE_NAME, _query=qs)
                exc_msg = msg % (request.url, exc_url)
                logger.exception(exc_msg)
                return response
            else:
                logger.exception('Exception at %s' % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            'pyramid_debugtoolbar:templates/redirect.mako', {
                                'redirect_to': redirect_to,
                                'redirect_code': redirect_code
                            },
                            request=request)
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            toolbar.process_response(response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
Exemple #23
0
def toolbar_tween_factory(handler, registry, _logger=None):
    """ Pyramid tween factory for the debug toolbar """
    # _logger passed for testing purposes only
    if _logger is None:
        _logger = logger
    settings = registry.settings

    if not get_setting(settings, 'enabled'):
        return handler

    request_history = ToolbarStorage(100)
    registry.request_history = request_history

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, 'panels', [])
    global_panel_classes = get_setting(settings, 'global_panels', [])
    intercept_exc = get_setting(settings, 'intercept_exc')
    intercept_redirects = get_setting(settings, 'intercept_redirects')
    show_on_exc_only = get_setting(settings, 'show_on_exc_only')
    hosts = get_setting(settings, 'hosts')
    auth_check = registry.queryUtility(IRequestAuthorization)
    exclude_prefixes = get_setting(settings, 'exclude_prefixes', [])
    registry.exc_history = exc_history = None
    registry.pdtb_token = hexlify(os.urandom(10))

    if intercept_exc:
        registry.exc_history = exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == 'debug'

    def toolbar_tween(request):
        request.exc_history = exc_history
        request.history = request_history
        root_url = request.route_path('debugtoolbar', subpath='')
        exclude = [root_url] + exclude_prefixes
        last_proxy_addr = None

        try:
            p = request.path
        except UnicodeDecodeError as e:
            raise URLDecodeError(e.encoding, e.object, e.start, e.end,
                                 e.reason)
        starts_with_excluded = list(filter(None, map(p.startswith, exclude)))

        if request.remote_addr:
            last_proxy_addr = last_proxy(request.remote_addr)

        if last_proxy_addr is None \
            or starts_with_excluded \
            or not addr_in(last_proxy_addr, hosts) \
            or auth_check and not auth_check(request):
            return handler(request)

        toolbar = DebugToolbar(request, panel_classes, global_panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        # XXX
        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
            toolbar.status_int = response.status_int
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(),
                                   skip=1,
                                   show_hidden_frames=False,
                                   ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame
                exc_history.tracebacks[tb.id] = tb
                request.pdbt_tb = tb

                qs = {'token': registry.pdtb_token, 'tb': str(tb.id)}
                msg = 'Exception at %s\ntraceback url: %s'
                exc_url = debug_toolbar_url(request, 'exception', _query=qs)
                exc_msg = msg % (request.url, exc_url)
                _logger.exception(exc_msg)

                subenviron = request.environ.copy()
                del subenviron['PATH_INFO']
                del subenviron['QUERY_STRING']
                subrequest = type(request).blank(exc_url, subenviron)
                response = request.invoke_subrequest(subrequest)

                toolbar.process_response(request, response)

                request.id = hexlify(id(request))
                toolbar.response = response
                toolbar.status_int = response.status_int

                request_history.put(request.id, toolbar)
                toolbar.inject(request, response)
                return response
            else:
                _logger.exception('Exception at %s' % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            'pyramid_debugtoolbar:templates/redirect.dbtmako',
                            {
                                'redirect_to': redirect_to,
                                'redirect_code': redirect_code,
                            },
                            request=request)
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            toolbar.process_response(request, response)
            request.id = hexlify(id(request))
            # Don't store the favicon.ico request
            # it's requested by the browser automatically
            if not "/favicon.ico" == request.path:
                toolbar.response = response
                request_history.put(request.id, toolbar)

            if not show_on_exc_only and response.content_type in html_types:
                toolbar.inject(request, response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
def toolbar_tween_factory(handler, registry):
    """ Pyramid tween factory for the debug toolbar """
    settings = registry.settings

    if not get_setting(settings, 'enabled'):
        return handler

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, 'panels', [])
    intercept_exc = get_setting(settings, 'intercept_exc')
    intercept_redirects = get_setting(settings, 'intercept_redirects')
    show_on_exc_only = get_setting(settings, 'show_on_exc_only')
    hosts = get_setting(settings, 'hosts')
    auth_check = registry.queryUtility(IRequestAuthorization)
    exclude_prefixes = get_setting(settings, 'exclude_prefixes', [])
    exc_history = None

    if intercept_exc:
        exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == 'debug'

    def toolbar_tween(request):
        root_path = request.route_path(ROOT_ROUTE_NAME)
        exclude = [root_path] + exclude_prefixes
        request.exc_history = exc_history
        last_proxy_addr = None

        try:
            p = request.path
        except UnicodeDecodeError as e:
            raise URLDecodeError(e.encoding, e.object, e.start, e.end, e.reason)
        
        starts_with_excluded = list(filter(None, map(p.startswith, exclude)))

        if request.remote_addr:
            last_proxy_addr = last_proxy(request.remote_addr)

        if last_proxy_addr is None \
            or starts_with_excluded \
            or not addr_in(last_proxy_addr, hosts) \
            or auth_check and not auth_check(request):
                return handler(request)

        toolbar = DebugToolbar(request, panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(),
                                   skip=1,
                                   show_hidden_frames=False,
                                   ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame

                exc_history.tracebacks[tb.id] = tb
                body = tb.render_full(request).encode('utf-8', 'replace')
                response = Response(body, status=500)
                toolbar.process_response(response)
                qs = {'token': exc_history.token, 'tb': str(tb.id)}
                msg = 'Exception at %s\ntraceback url: %s'
                exc_url = request.route_url(EXC_ROUTE_NAME, _query=qs)
                exc_msg = msg % (request.url, exc_url)
                logger.exception(exc_msg)
                return response
            else:
                logger.exception('Exception at %s' % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            'pyramid_debugtoolbar:templates/redirect.dbtmako',
                            {'redirect_to': redirect_to,
                            'redirect_code': redirect_code},
                            request=request)
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            if not show_on_exc_only:
                toolbar.process_response(response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
def toolbar_handler_factory(handler, registry):
    settings = registry.settings

    if not get_setting(settings, "enabled"):
        return handler

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, "panels", [])
    intercept_exc = get_setting(settings, "intercept_exc")
    intercept_redirects = get_setting(settings, "intercept_redirects")
    hosts = get_setting(settings, "hosts")

    exc_history = None

    if intercept_exc:
        exc_history = ExceptionHistory()

    def toolbar_handler(request):
        root_path = request.route_path("debugtoolbar.root")
        request.exc_history = exc_history
        remote_addr = request.remote_addr

        if request.path.startswith(root_path) or (not remote_addr in hosts):
            return handler(request)

        toolbar = DebugToolbar(request, panel_classes)
        request.debug_toolbar = toolbar

        _handler = handler

        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
        except Exception:
            info = sys.exc_info()
            if exc_history is not None:
                tb = get_traceback(info=info, skip=1, show_hidden_frames=False, ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame

                exc_history.tracebacks[tb.id] = tb
                body = tb.render_full(request, evalex=True).encode("utf-8", "replace")
                response = Response(body, status=500)
                toolbar.process_response(response)
                return response

            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            "pyramid_debugtoolbar:templates/redirect.jinja2",
                            {"redirect_to": redirect_to, "redirect_code": redirect_code},
                        )
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            toolbar.process_response(response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_handler
def toolbar_tween_factory(handler, registry):
    """ Pyramid tween factory for the debug toolbar """
    settings = registry.settings

    if not get_setting(settings, 'enabled'):
        return handler

    redirect_codes = (301, 302, 303, 304)
    panel_classes = get_setting(settings, 'panels', [])
    intercept_exc = get_setting(settings, 'intercept_exc')
    intercept_redirects = get_setting(settings, 'intercept_redirects')
    hosts = get_setting(settings, 'hosts')

    exc_history = None

    if intercept_exc:
        exc_history = ExceptionHistory()
        exc_history.eval_exc = intercept_exc == 'debug'

    def toolbar_tween(request):
        root_path = request.route_path(ROOT_ROUTE_NAME)
        request.exc_history = exc_history
        remote_addr = request.remote_addr

        if remote_addr is None or request.path.startswith(root_path):
            return handler(request)
        else:
            for host in hosts:
                if ipaddr.IPAddress(remote_addr) in ipaddr.IPNetwork(host):
                    break
            else:
                return handler(request)

        toolbar = DebugToolbar(request, panel_classes)
        request.debug_toolbar = toolbar
        
        _handler = handler

        for panel in toolbar.panels:
            _handler = panel.wrap_handler(_handler)

        try:
            response = _handler(request)
        except Exception:
            if exc_history is not None:
                tb = get_traceback(info=sys.exc_info(),
                                   skip=1,
                                   show_hidden_frames=False,
                                   ignore_system_exceptions=True)
                for frame in tb.frames:
                    exc_history.frames[frame.id] = frame

                exc_history.tracebacks[tb.id] = tb
                body = tb.render_full(request).encode('utf-8', 'replace')
                response = Response(body, status=500)
                toolbar.process_response(response)
                qs = {'token':exc_history.token, 'tb':str(tb.id)}
                msg = 'Exception at %s\ntraceback url: %s' 
                exc_url = request.route_url(EXC_ROUTE_NAME, _query=qs)
                exc_msg = msg % (request.url, exc_url)
                logger.exception(exc_msg)
                return response
            else:
                logger.exception('Exception at %s' % request.url)
            raise

        else:
            if intercept_redirects:
                # Intercept http redirect codes and display an html page with a
                # link to the target.
                if response.status_int in redirect_codes:
                    redirect_to = response.location
                    redirect_code = response.status_int
                    if redirect_to:
                        content = render(
                            'pyramid_debugtoolbar:templates/redirect.dbtmako',
                            {'redirect_to': redirect_to,
                            'redirect_code': redirect_code},
                            request=request)
                        content = content.encode(response.charset)
                        response.content_length = len(content)
                        response.location = None
                        response.app_iter = [content]
                        response.status_int = 200

            toolbar.process_response(response)
            return response

        finally:
            # break circref
            del request.debug_toolbar

    return toolbar_tween
Exemple #27
0
 def sget(opt, default=None):
     return get_setting(settings, opt, default)
Exemple #28
0
def valid_host(info, request):
    hosts = get_setting(request.registry.settings, 'hosts')
    if request.remote_addr in hosts:
        return True
    return False
Exemple #29
0
def valid_host(info, request):
    hosts = get_setting(request.registry.settings, 'hosts')
    if request.remote_addr in hosts:
        return True
    return False