예제 #1
0
    def __call__(self, value, system):
        context = system.pop('context', None)
        if context is not None:
            system['_context'] = context
        # tuple returned to be deprecated
        if isinstance(value, tuple):
            self.warnings.warn(
                'Using a tuple in the form (\'defname\', {}) to render a '
                'Mako partial will be deprecated in the future. Use a '
                'Mako template renderer as documented in the "Using A '
                'Mako def name Within a Renderer Name" chapter of the '
                'Pyramid narrative documentation instead', DeprecationWarning,
                3)
            self.defname, value = value
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        template = self.implementation()
        if self.defname is not None:
            template = template.get_def(self.defname)
        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = text_error_template().render(error=exc_info[1],
                                                       traceback=exc_info[2])
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #2
0
    def handled_exception_tween(request):
        try:
            response = handler(request)

            if isinstance(response, httpexceptions.HTTPError):
                eresp = err_response(request, IUserException(response),
                                     response, None)
                if eresp is not None:
                    return eresp

            return response

        except Exception as exc:
            exc_info = sys.exc_info()

            if request.path_info.startswith('/test/request/'):
                reraise(*exc_info)

            try:
                err_info = IUserException(exc)
            except TypeError:
                err_info = None

            if err_info is not None:
                eresp = err_response(request, err_info, exc, exc_info)
                if eresp is not None:
                    return eresp

            reraise(*exc_info)
예제 #3
0
    def __call__(self, value, system):
        # Update the system dictionary with the values from the user
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')

        # Check if 'context' in the dictionary
        context = system.pop('context', None)

        # Rename 'context' to '_context' because Mako internally already has a
        # variable named 'context'
        if context is not None:
            system['_context'] = context

        template = self.template
        if self.defname is not None:
            template = template.get_def(self.defname)
        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = text_error_template().render(error=exc_info[1],
                                                       traceback=exc_info[2])
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #4
0
    def __call__(self, value, system):
        context = system.pop('context', None)
        if context is not None:
            system['_context'] = context
        def_name = None
        if isinstance(value, tuple):
            def_name, value = value
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        template = self.implementation()
        if def_name is not None:
            template = template.get_def(def_name)
        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = exceptions.text_error_template().render(
                    error=exc_info[1],
                    traceback=exc_info[2]
                    )
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #5
0
 def __call__(self, request):
     self.client.begin_transaction('request')
     try:
         response = self.handler(request)
         transaction_result = response.status[0] + "xx"
         elasticapm.set_context(lambda: get_data_from_response(response), "response")
         return response
     except Exception:  # pylint: disable=broad-except
         transaction_result = '5xx'
         self.client.capture_exception(
             context={
                 "request": get_data_from_request(request)
             },
             handled=False,  # indicate that this exception bubbled all the way up to the user
         )
         reraise(*sys.exc_info())
     finally:
         try:
             view_name = request.view_name
             if not view_name:
                 view_name = request.traversed[-1] if request.traversed else '/'
         except AttributeError:
             view_name = ''
         transaction_name = request.matched_route.pattern if request.matched_route else view_name
         # prepend request method
         transaction_name = " ".join((request.method, transaction_name)) \
             if transaction_name else ""
         elasticapm.set_context(lambda: get_data_from_request(request), "request")
         self.client.end_transaction(transaction_name, transaction_result)
예제 #6
0
    def __call__(self, value, system):
        context = system.pop('context', None)
        if context is not None:
            system['_context'] = context
        if self.defname is None:
            if isinstance(value, tuple):
                self.defname, value = value
        else:
            if isinstance(value, tuple):
                _, value = value
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')
        template = self.implementation()
        if self.defname is not None:
            template = template.get_def(self.defname)
        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = exceptions.text_error_template().render(
                    error=exc_info[1], traceback=exc_info[2])
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #7
0
    def __call__(self, value, system):
        # Update the system dictionary with the values from the user
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')

        # Check if 'context' in the dictionary
        context = system.pop('context', None)

        # Rename 'context' to '_context' because Mako internally already has a
        # variable named 'context'
        if context is not None:
            system['_context'] = context

        template = self.template
        if self.defname is not None:
            template = template.get_def(self.defname)
        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = text_error_template().render(
                    error=exc_info[1],
                    traceback=exc_info[2]
                    )
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #8
0
파일: router.py 프로젝트: matkins/pyramid
def default_execution_policy(environ, router):
    request = router.make_request(environ)
    try:
        return router.invoke_request(request)
    except Exception:
        exc_info = sys.exc_info()
        try:
            return request.invoke_exception_view(exc_info)
        except HTTPNotFound:
            reraise(*exc_info)
        finally:
            del exc_info  # avoid local ref cycle
예제 #9
0
    def __call__(self, value, system):
        """Find and render a template.

        This replaces the default Mako renderer to locate templates by theme.

        ``system`` will contain default renderer globals plus those added by
        by :func:`add_renderer_globals`.

        ``value`` will be either the dict returned from a view or the dict
        passed to one of Pyramid's render functions. These values will
        override the ``system`` values.

        :func:`add_renderer_globals` will be called to update ``system``
        before this method is called; it can access ``value`` via
        ``event.rendering_val``.

        """
        # Avoid conflict between Pyramid and Mako ``context``s
        system['_context'] = system.pop('context', None)

        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')

        request = system['request']

        theme = request.theme
        if self.plaintext:
            lookup = theme.lookup_nofilters
            response = request.response
            ct = response.content_type
            if ct == response.default_content_type:
                response.content_type = 'text/plain'
        else:
            lookup = theme.lookup

        template = lookup.get_template(self.name)

        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = exceptions.text_error_template().render(
                    error=exc_info[1],
                    traceback=exc_info[2])
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #10
0
def _error_handler(request, exc):
    # NOTE: we do not need to delete exc_info because this function
    # should never be in the call stack of the exception
    exc_info = sys.exc_info()

    try:
        response = request.invoke_exception_view(exc_info)
    except HTTPNotFound:
        # re-raise the original exception as no exception views were
        # able to handle the error
        reraise(*exc_info)

    return response
예제 #11
0
파일: tweens.py 프로젝트: JDeuce/pyramid
def _error_handler(request, exc):
    # NOTE: we do not need to delete exc_info because this function
    # should never be in the call stack of the exception
    exc_info = sys.exc_info()

    try:
        response = request.invoke_exception_view(exc_info)
    except HTTPNotFound:
        # re-raise the original exception as no exception views were
        # able to handle the error
        reraise(*exc_info)

    return response
예제 #12
0
    def excview_tween(request):
        attrs = request.__dict__
        try:
            response = handler(request)
        except Exception as exc:
            # WARNING: do not assign the result of sys.exc_info() to a local
            # var here, doing so will cause a leak.  We used to actually
            # explicitly delete both "exception" and "exc_info" from ``attrs``
            # in a ``finally:`` clause below, but now we do not because these
            # attributes are useful to upstream tweens.  This actually still
            # apparently causes a reference cycle, but it is broken
            # successfully by the garbage collector (see
            # https://github.com/Pylons/pyramid/issues/1223).
            attrs['exc_info'] = sys.exc_info()
            attrs['exception'] = exc
            # clear old generated request.response, if any; it may
            # have been mutated by the view, and its state is not
            # sane (e.g. caching headers)
            status_api = request.response.status_int
            if 'response' in attrs:
                del attrs['response']
            # we use .get instead of .__getitem__ below due to
            # https://github.com/Pylons/pyramid/issues/700

            request_iface = attrs.get('request_iface', IRequest)
            provides = providedBy(exc)
            if status_api == 406:
                request.response.status_int = 406
            try:
                response = _call_view(registry,
                                      request,
                                      exc,
                                      provides,
                                      '',
                                      view_classifier=IExceptionViewClassifier,
                                      request_iface=request_iface.combined)

            # if views matched but did not pass predicates, squash the error
            # and re-raise the original exception
            except PredicateMismatch:
                response = None

            # re-raise the original exception as no exception views were
            # able to handle the error
            if response is None:
                reraise(*attrs['exc_info'])

        return response
예제 #13
0
    def __call__(self, value, system):
        """Find and render a template.

        This replaces the default Mako renderer to locate templates by theme.

        ``system`` will contain default renderer globals plus those added by
        by :func:`add_renderer_globals`.

        ``value`` will be either the dict returned from a view or the dict
        passed to one of Pyramid's render functions. These values will
        override the ``system`` values.

        :func:`add_renderer_globals` will be called to update ``system``
        before this method is called; it can access ``value`` via
        ``event.rendering_val``.

        """
        # Avoid conflict between Pyramid and Mako ``context``s
        system['_context'] = system.pop('context', None)

        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')

        request = system['request']

        theme = request.theme
        if self.clear_default_filters:
            lookup = theme.lookup_nofilters
        else:
            lookup = theme.lookup

        template = lookup.get_template(self.name)

        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = exceptions.text_error_template().render(
                    error=exc_info[1], traceback=exc_info[2])
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #14
0
    def excview_tween(request):
        attrs = request.__dict__
        try:
            response = handler(request)
        except Exception as exc:
            # WARNING: do not assign the result of sys.exc_info() to a local
            # var here, doing so will cause a leak.  We used to actually
            # explicitly delete both "exception" and "exc_info" from ``attrs``
            # in a ``finally:`` clause below, but now we do not because these
            # attributes are useful to upstream tweens.  This actually still
            # apparently causes a reference cycle, but it is broken
            # successfully by the garbage collector (see
            # https://github.com/Pylons/pyramid/issues/1223).
            attrs['exc_info'] = sys.exc_info()
            attrs['exception'] = exc
            # clear old generated request.response, if any; it may
            # have been mutated by the view, and its state is not
            # sane (e.g. caching headers)
            if 'response' in attrs:
                del attrs['response']
            # we use .get instead of .__getitem__ below due to
            # https://github.com/Pylons/pyramid/issues/700
            request_iface = attrs.get('request_iface', IRequest)
            provides = providedBy(exc)
            try:
                response = _call_view(
                    registry,
                    request,
                    exc,
                    provides,
                    '',
                    view_classifier=IExceptionViewClassifier,
                    request_iface=request_iface.combined
                    )

            # if views matched but did not pass predicates, squash the error
            # and re-raise the original exception
            except PredicateMismatch:
                response = None

            # re-raise the original exception as no exception views were
            # able to handle the error
            if response is None:
                reraise(*attrs['exc_info'])

        return response
예제 #15
0
    def unhandled_exception_tween(request):
        try:
            return handler(request)
        except Exception as exc:
            if request.path_info.startswith('/test/request/'):
                reraise(*sys.exc_info())

            try:
                _logger.exception("Uncaught exception %s at %s" %
                                  (exc_name(exc), request.url))
                iexc = InternalServerError(sys.exc_info())
                return exc_response(request, iexc, iexc, iexc.exc_info)
            except Exception:
                _logger.exception(
                    "Exception while rendering error response at %s",
                    request.url)
                return httpexceptions.HTTPInternalServerError()
예제 #16
0
    def __call__(self, value, system):
        # tuple returned to be deprecated
        if isinstance(value, tuple):
            self.warnings.warn(
                'Using a tuple in the form (\'defname\', {}) to render a '
                'Mako partial will be deprecated in the future. Use a '
                'Mako template renderer as documented in the "Using A '
                'Mako def name Within a Renderer Name" chapter of the '
                'Pyramid narrative documentation instead',
                DeprecationWarning,
                3)
            self.defname, value = value
        # Update the system dictionary with the values from the user
        try:
            system.update(value)
        except (TypeError, ValueError):
            raise ValueError('renderer was passed non-dictionary as value')

        # Check if 'context' in the dictionary
        context = system.pop('context', None)

        # Rename 'context' to '_context' because Mako internally already has a
        # variable named 'context'
        if context is not None:
            system['_context'] = context

        template = self.template
        if self.defname is not None:
            template = template.get_def(self.defname)
        try:
            result = template.render_unicode(**system)
        except:
            try:
                exc_info = sys.exc_info()
                errtext = text_error_template().render(
                    error=exc_info[1],
                    traceback=exc_info[2]
                    )
                reraise(MakoRenderingException(errtext), None, exc_info[2])
            finally:
                del exc_info

        return result
예제 #17
0
 def __init__(self, *arg, **kw):
     reraise(ImportError, exc, tb)
예제 #18
0
    def execute_actions(self, clear=True, introspector=None):
        """Execute the configuration actions

        This calls the action callables after resolving conflicts

        For example:

        >>> output = []
        >>> def f(*a, **k):
        ...    output.append(('f', a, k))
        >>> context = ActionState()
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   ]
        >>> context.execute_actions()
        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        If the action raises an error, we convert it to a
        ConfigurationExecutionError.

        >>> output = []
        >>> def bad():
        ...    bad.xxx
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   (3, bad, (), {}, (), 'oops')
        ...   ]
        >>> try:
        ...    v = context.execute_actions()
        ... except ConfigurationExecutionError, v:
        ...    pass
        >>> print(v)
        exceptions.AttributeError: 'function' object has no attribute 'xxx'
          in:
          oops

        Note that actions executed before the error still have an effect:

        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        The execution is re-entrant such that actions may be added by other
        actions with the one caveat that the order of any added actions must
        be equal to or larger than the current action.

        >>> output = []
        >>> def f(*a, **k):
        ...   output.append(('f', a, k))
        ...   context.actions.append((3, g, (8,), {}))
        >>> def g(*a, **k):
        ...    output.append(('g', a, k))
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   ]
        >>> context.execute_actions()
        >>> output
        [('f', (1,), {}), ('g', (8,), {})]

        """
        try:
            all_actions = []
            executed_actions = []
            action_iter = iter([])
            conflict_state = ConflictResolverState()

            while True:
                # We clear the actions list prior to execution so if there
                # are some new actions then we add them to the mix and resolve
                # conflicts again. This orders the new actions as well as
                # ensures that the previously executed actions have no new
                # conflicts.
                if self.actions:
                    all_actions.extend(self.actions)
                    action_iter = resolveConflicts(
                        self.actions, state=conflict_state
                    )
                    self.actions = []

                action = next(action_iter, None)
                if action is None:
                    # we are done!
                    break

                callable = action['callable']
                args = action['args']
                kw = action['kw']
                info = action['info']
                # we use "get" below in case an action was added via a ZCML
                # directive that did not know about introspectables
                introspectables = action.get('introspectables', ())

                try:
                    if callable is not None:
                        callable(*args, **kw)
                except Exception:
                    t, v, tb = sys.exc_info()
                    try:
                        reraise(
                            ConfigurationExecutionError,
                            ConfigurationExecutionError(t, v, info),
                            tb,
                        )
                    finally:
                        del t, v, tb

                if introspector is not None:
                    for introspectable in introspectables:
                        introspectable.register(introspector, info)

                executed_actions.append(action)

            self.actions = all_actions
            return executed_actions

        finally:
            if clear:
                self.actions = []
예제 #19
0
 def json_body(req):
     try:
         return json.loads(req.body, encoding=req.charset)
     except ValueError as exc:
         user_exception(exc, title="JSON parse error", http_status_code=400)
         reraise(*sys.exc_info())
예제 #20
0
    def execute_actions(self, clear=True):
        """Execute the configuration actions

        This calls the action callables after resolving conflicts

        For example:

        >>> output = []
        >>> def f(*a, **k):
        ...    output.append(('f', a, k))
        >>> context = ActionState()
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   ]
        >>> context.execute_actions()
        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        If the action raises an error, we convert it to a
        ConfigurationExecutionError.

        >>> output = []
        >>> def bad():
        ...    bad.xxx
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   (3, bad, (), {}, (), 'oops')
        ...   ]
        >>> try:
        ...    v = context.execute_actions()
        ... except ConfigurationExecutionError, v:
        ...    pass
        >>> print v
        exceptions.AttributeError: 'function' object has no attribute 'xxx'
          in:
          oops


        Note that actions executed before the error still have an effect:

        >>> output
        [('f', (1,), {}), ('f', (2,), {})]


        """
        try:
            for action in resolveConflicts(self.actions):
                _, callable, args, kw, _, info, _ = expand_action(*action)
                if callable is None:
                    continue
                try:
                    callable(*args, **kw)
                except (KeyboardInterrupt, SystemExit): # pragma: no cover
                    raise
                except:
                    t, v, tb = sys.exc_info()
                    try:
                        reraise(ConfigurationExecutionError,
                                ConfigurationExecutionError(t, v, info),
                                tb)
                    finally:
                       del t, v, tb
        finally:
            if clear:
                del self.actions[:]
예제 #21
0
파일: __init__.py 프로젝트: AvdN/pyramid
    def execute_actions(self, clear=True, introspector=None):
        """Execute the configuration actions

        This calls the action callables after resolving conflicts

        For example:

        >>> output = []
        >>> def f(*a, **k):
        ...    output.append(('f', a, k))
        >>> context = ActionState()
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   ]
        >>> context.execute_actions()
        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        If the action raises an error, we convert it to a
        ConfigurationExecutionError.

        >>> output = []
        >>> def bad():
        ...    bad.xxx
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   (3, bad, (), {}, (), 'oops')
        ...   ]
        >>> try:
        ...    v = context.execute_actions()
        ... except ConfigurationExecutionError, v:
        ...    pass
        >>> print(v)
        exceptions.AttributeError: 'function' object has no attribute 'xxx'
          in:
          oops

        Note that actions executed before the error still have an effect:

        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        """

        try:
            for action in resolveConflicts(self.actions):
                callable = action['callable']
                args = action['args']
                kw = action['kw']
                info = action['info']
                # we use "get" below in case an action was added via a ZCML
                # directive that did not know about introspectables
                introspectables = action.get('introspectables', ())

                try:
                    if callable is not None:
                        callable(*args, **kw)
                except (KeyboardInterrupt, SystemExit): # pragma: no cover
                    raise
                except:
                    t, v, tb = sys.exc_info()
                    try:
                        reraise(ConfigurationExecutionError,
                                ConfigurationExecutionError(t, v, info),
                                tb)
                    finally:
                       del t, v, tb

                if introspector is not None:
                    for introspectable in introspectables:
                        introspectable.register(introspector, info)
                
        finally:
            if clear:
                del self.actions[:]
예제 #22
0
    def execute_actions(self, clear=True, introspector=None):
        """Execute the configuration actions

        This calls the action callables after resolving conflicts

        For example:

        >>> output = []
        >>> def f(*a, **k):
        ...    output.append(('f', a, k))
        >>> context = ActionState()
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   ]
        >>> context.execute_actions()
        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        If the action raises an error, we convert it to a
        ConfigurationExecutionError.

        >>> output = []
        >>> def bad():
        ...    bad.xxx
        >>> context.actions = [
        ...   (1, f, (1,)),
        ...   (1, f, (11,), {}, ('x', )),
        ...   (2, f, (2,)),
        ...   (3, bad, (), {}, (), 'oops')
        ...   ]
        >>> try:
        ...    v = context.execute_actions()
        ... except ConfigurationExecutionError, v:
        ...    pass
        >>> print v
        exceptions.AttributeError: 'function' object has no attribute 'xxx'
          in:
          oops

        Note that actions executed before the error still have an effect:

        >>> output
        [('f', (1,), {}), ('f', (2,), {})]

        """

        try:
            for action in resolveConflicts(self.actions):
                callable = action['callable']
                args = action['args']
                kw = action['kw']
                info = action['info']
                # we use "get" below in case an action was added via a ZCML
                # directive that did not know about introspectables
                introspectables = action.get('introspectables', ())

                try:
                    if callable is not None:
                        callable(*args, **kw)
                except (KeyboardInterrupt, SystemExit):  # pragma: no cover
                    raise
                except:
                    t, v, tb = sys.exc_info()
                    try:
                        reraise(ConfigurationExecutionError,
                                ConfigurationExecutionError(t, v, info), tb)
                    finally:
                        del t, v, tb

                if introspector is not None:
                    for introspectable in introspectables:
                        introspectable.register(introspector, info)

        finally:
            if clear:
                del self.actions[:]
예제 #23
0
 def __init__(self, *arg, **kw):
     reraise(ImportError, exc, tb)