コード例 #1
0
    def _makeRequest(self):
        from pyramid_debugtoolbar.utils import ToolbarStorage
        request = testing.DummyRequest()
        request.matchdict['request_id'] = 'reqid'
        request.matchdict['frame_id'] = '0'

        toolbar = DummyToolbar()
        toolbar.traceback = self._makeTraceback('tbid')

        history = ToolbarStorage(10)
        history.put('reqid', toolbar)
        request.pdtb_history = history
        return request
コード例 #2
0
    def _makeRequest(self):
        from pyramid_debugtoolbar.utils import ToolbarStorage
        request = testing.DummyRequest()
        request.matchdict['request_id'] = 'reqid'
        request.matchdict['frame_id'] = '0'

        toolbar = DummyToolbar()
        toolbar.traceback = self._makeTraceback('tbid')

        history = ToolbarStorage(10)
        history.put('reqid', toolbar)
        request.pdtb_history = history
        return request
コード例 #3
0
ファイル: toolbar.py プロジェクト: bmonteiro00/geru
def toolbar_tween_factory(handler, registry, _logger=None, _dispatch=None):
    """ Pyramid tween factory for the debug toolbar """
    # _logger and _dispatch are passed for testing purposes only
    if _logger is None:
        _logger = logger
    if _dispatch is None:
        _dispatch = lambda app, request: request.get_response(app)
    settings = registry.settings

    def sget(opt, default=None):
        return get_setting(settings, opt, default)

    if not sget('enabled'):
        return handler

    toolbar_app = registry.getUtility(IToolbarWSGIApp)
    toolbar_registry = toolbar_app.registry

    max_request_history = sget('max_request_history')
    request_history = ToolbarStorage(max_request_history)
    registry.pdtb_history = request_history

    panel_map = toolbar_registry.queryUtility(IPanelMap, default={})
    resolve_panels = lambda a, b: resolve_panel_classes(a, b, panel_map)

    panel_classes = list(sget('panels', []))
    if not panel_classes:
        # if no panels are defined then use all available panels
        panel_classes = [p for p, g in panel_map if not g]
    panel_classes.extend(sget('extra_panels', []))
    panel_classes = resolve_panels(panel_classes, False)
    global_panel_classes = list(sget('global_panels', []))
    if not global_panel_classes:
        # if no panels are defined then use all available global panels
        global_panel_classes = [p for p, g in panel_map if g]
    global_panel_classes.extend(sget('extra_global_panels', []))
    global_panel_classes = resolve_panels(global_panel_classes, True)

    redirect_codes = (301, 302, 303, 304)
    intercept_exc = sget('intercept_exc')
    intercept_redirects = sget('intercept_redirects')
    show_on_exc_only = sget('show_on_exc_only')
    hosts = sget('hosts')
    auth_check = registry.queryUtility(IRequestAuthorization)
    exclude_prefixes = sget('exclude_prefixes', [])
    registry.pdtb_token = hexlify(os.urandom(5))
    registry.pdtb_eval_exc = intercept_exc

    default_active_panels = sget('active_panels', [])

    dispatch = lambda request: _dispatch(toolbar_app, request)

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

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

        if (
            last_proxy_addr is None
            or any(p.startswith(e) for e in exclude_prefixes)
            or not addr_in(last_proxy_addr, hosts)
            or auth_check and not auth_check(request)
        ):
            return handler(request)

        if request.environ.get('wsgi.multiprocess', False):
            warnings.warn(
                'pyramid_debugtoolbar has detected that the application is '
                'being served by a forking / multiprocess web server. The '
                'toolbar relies on global state to work and is not compatible '
                'with this environment. The toolbar will be disabled.')
            return handler(request)

        root_path = debug_toolbar_url(request, '', _app_url='')
        if p.startswith(root_path):
            # we know root_path will always have a trailing slash
            # but script_name doesn't want it
            try:
                old_script_name = request.script_name
                old_path_info = request.path_info
                request.script_name += root_path[:-1]
                request.path_info = request.path_info[len(root_path) - 1:]
                return dispatch(request)
            finally:
                request.script_name = old_script_name
                request.path_info = old_path_info

        request.pdtb_id = hexlify(id(request))
        toolbar = DebugToolbar(request, panel_classes, global_panel_classes,
                               default_active_panels)
        request.debug_toolbar = toolbar
        request_history.put(request.pdtb_id, toolbar)

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

        try:
            response = _handler(request)
            toolbar.status_int = response.status_int

            if request.exc_info and intercept_exc:
                toolbar.traceback = process_traceback(request.exc_info)

                msg = 'Squashed %s at %s\ntraceback url: %s'
                exc_name = get_exc_name(request.exc_info[1])
                subrequest = make_subrequest(
                    request, root_path, request.pdtb_id + '/exception')
                exc_msg = msg % (exc_name, request.url, subrequest.url)
                _logger.info(exc_msg)

        except Exception as exc:
            exc_name = get_exc_name(exc)
            if intercept_exc:
                toolbar.traceback = process_traceback(sys.exc_info())

                msg = 'Uncaught %s at %s\ntraceback url: %s'
                subrequest = make_subrequest(
                    request, root_path, request.pdtb_id + '/exception')
                exc_msg = msg % (exc_name, request.url, subrequest.url)
                _logger.exception(exc_msg)

                response = dispatch(subrequest)
                toolbar.status_int = response.status_int

                # The original request must be processed so that the panel
                # data exists if the request is later examined in the full
                # toolbar view.
                toolbar.process_response(request, response)

                # Inject the button to activate the full toolbar view.
                toolbar.inject(request, response)
                return response

            else:
                msg = 'Uncaught %s at %s'
                _logger.exception(msg % (exc_name, 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:
                        qs = {
                            'redirect_to': redirect_to,
                            'redirect_code': str(redirect_code),
                        }
                        subrequest = make_subrequest(
                            request, root_path, 'redirect', qs)
                        content = dispatch(subrequest).text
                        response.location = None
                        response.text = content
                        response.status_int = 200

            toolbar.process_response(request, response)

            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
コード例 #4
0
ファイル: toolbar.py プロジェクト: bishwa3141/movie
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

    def sget(opt, default=None):
        return get_setting(settings, opt, default)

    if not sget('enabled'):
        return handler

    max_request_history = sget('max_request_history')
    request_history = ToolbarStorage(max_request_history)
    registry.request_history = request_history

    redirect_codes = (301, 302, 303, 304)
    panel_classes = sget('panels', [])
    panel_classes.extend(sget('extra_panels', []))
    global_panel_classes = sget('global_panels', [])
    global_panel_classes.extend(sget('extra_global_panels', []))
    intercept_exc = sget('intercept_exc')
    intercept_redirects = sget('intercept_redirects')
    show_on_exc_only = sget('show_on_exc_only')
    hosts = sget('hosts')
    auth_check = registry.queryUtility(IRequestAuthorization)
    exclude_prefixes = sget('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)
                subrequest.script_name = request.script_name
                subrequest.path_info = \
                    subrequest.path_info[len(request.script_name):]
                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
コード例 #5
0
def toolbar_tween_factory(handler, registry, _logger=None, _dispatch=None):
    """ Pyramid tween factory for the debug toolbar """
    # _logger and _dispatch are passed for testing purposes only
    if _logger is None:
        _logger = logger
    if _dispatch is None:
        _dispatch = lambda app, request: request.get_response(app)
    settings = registry.settings

    def sget(opt, default=None):
        return get_setting(settings, opt, default)

    if not sget('enabled'):
        return handler

    max_request_history = sget('max_request_history')
    request_history = ToolbarStorage(max_request_history)
    registry.request_history = request_history

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

    default_active_panels = sget('active_panels', [])

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

    toolbar_app = registry.getUtility(IToolbarWSGIApp)
    dispatch = lambda request: _dispatch(toolbar_app, request)

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

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

        if (last_proxy_addr is None
                or any(p.startswith(e) for e in exclude_prefixes)
                or not addr_in(last_proxy_addr, hosts)
                or auth_check and not auth_check(request)):
            return handler(request)

        root_path = debug_toolbar_url(request, '', _app_url='')
        if p.startswith(root_path):
            # we know root_path will always have a trailing slash
            # but script_name doesn't want it
            try:
                old_script_name = request.script_name
                old_path_info = request.path_info
                request.script_name += root_path[:-1]
                request.path_info = request.path_info[len(root_path) - 1:]
                return dispatch(request)
            finally:
                request.script_name = old_script_name
                request.path_info = old_path_info

        request.exc_history = exc_history
        request.history = request_history
        request.pdtb_id = hexlify(id(request))
        toolbar = DebugToolbar(request, panel_classes, global_panel_classes,
                               default_active_panels)
        request.debug_toolbar = toolbar

        _handler = handler
        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

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

                response = dispatch(subrequest)

                # The original request must be processed so that the panel data exists
                # if the request is later examined in the full toolbar view.
                toolbar.process_response(request, response)

                toolbar.response = response
                toolbar.status_int = response.status_int

                request_history.put(request.pdtb_id, toolbar)
                # Inject the button to activate the full toolbar view.
                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:
                        qs = {
                            'token': registry.pdtb_token,
                            'redirect_to': redirect_to,
                            'redirect_code': str(redirect_code),
                        }
                        subrequest = make_subrequest(request, root_path,
                                                     'redirect', qs)
                        content = dispatch(subrequest).text
                        response.location = None
                        response.text = content
                        response.status_int = 200

            toolbar.process_response(request, response)
            # 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.pdtb_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