Esempio n. 1
0
File: hooks.py Progetto: nZac/falcon
def _wrap_with_after(responder, action, action_args, action_kwargs):
    """Execute the given action function after a responder method.

    Args:
        responder: The responder method to wrap.
        action: A function with a signature similar to a resource responder
            method, taking the form ``func(req, resp, resource)``.
        action_args: Additional positional agruments to pass to *action*.
        action_kwargs: Additional keyword arguments to pass to *action*.
    """

    responder_argnames = get_argnames(responder)
    extra_argnames = responder_argnames[2:]  # Skip req, resp

    if iscoroutinefunction(responder):
        action = _wrap_non_coroutine_unsafe(action)

        @wraps(responder)
        async def do_after(self, req, resp, *args, **kwargs):
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            await responder(self, req, resp, **kwargs)
            await action(req, resp, self, *action_args, **action_kwargs)
    else:

        @wraps(responder)
        def do_after(self, req, resp, *args, **kwargs):
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            responder(self, req, resp, **kwargs)
            action(req, resp, self, *action_args, **action_kwargs)

    return do_after
Esempio n. 2
0
File: app.py Progetto: nZac/falcon
    def add_error_handler(self, exception, handler=None):
        if not handler:
            try:
                handler = exception.handle
            except AttributeError:
                # NOTE(kgriffs): Delegate to the parent method for error handling.
                pass

        handler = _wrap_non_coroutine_unsafe(handler)

        if handler and not iscoroutinefunction(handler):
            raise CompatibilityError(
                'The handler must be an awaitable coroutine function in order '
                'to be used safely with an ASGI app.')

        super().add_error_handler(exception, handler=handler)
Esempio n. 3
0
File: hooks.py Progetto: wsz/falcon
def _wrap_with_before(responder, action, action_args, action_kwargs, is_async):
    """Execute the given action function before a responder method.

    Args:
        responder: The responder method to wrap.
        action: A function with a similar signature to a resource responder
            method, taking the form ``func(req, resp, resource, params)``.
        action_args: Additional positional agruments to pass to *action*.
        action_kwargs: Additional keyword arguments to pass to *action*.
        is_async: Set to ``True`` for cythonized responders that are
            actually coroutine functions, since such responders can not
            be auto-detected. A hint is also required for regular functions
            that happen to return an awaitable coroutine object.
    """

    responder_argnames = get_argnames(responder)
    extra_argnames = responder_argnames[2:]  # Skip req, resp

    if is_async or iscoroutinefunction(responder):
        # NOTE(kgriffs): I manually verified that the implicit "else" branch
        #   is actually covered, but coverage isn't tracking it for
        #   some reason.
        if not is_async:  # pragma: nocover
            action = _wrap_non_coroutine_unsafe(action)

        @wraps(responder)
        async def do_before(self, req, resp, *args, **kwargs):
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            await action(req, resp, self, kwargs, *action_args,
                         **action_kwargs)
            await responder(self, req, resp, **kwargs)

    else:

        @wraps(responder)
        def do_before(self, req, resp, *args, **kwargs):
            if args:
                _merge_responder_args(args, kwargs, extra_argnames)

            action(req, resp, self, kwargs, *action_args, **action_kwargs)
            responder(self, req, resp, **kwargs)

    return do_before
Esempio n. 4
0
    def add_error_handler(self, exception, handler=None):
        """Register a handler for one or more exception types.

        Error handlers may be registered for any exception type, including
        :class:`~.HTTPError` or :class:`~.HTTPStatus`. This feature
        provides a central location for logging and otherwise handling
        exceptions raised by responders, hooks, and middleware components.

        A handler can raise an instance of :class:`~.HTTPError` or
        :class:`~.HTTPStatus` to communicate information about the issue to
        the client.  Alternatively, a handler may modify `resp`
        directly.

        An error handler "matches" a raised exception if the exception is an
        instance of the corresponding exception type. If more than one error
        handler matches the raised exception, the framework will choose the
        most specific one, as determined by the method resolution order of the
        raised exception type. If multiple error handlers are registered for the
        *same* exception class, then the most recently-registered handler is
        used.

        For example, suppose we register error handlers as follows::

            app = App()
            app.add_error_handler(falcon.HTTPNotFound, custom_handle_not_found)
            app.add_error_handler(falcon.HTTPError, custom_handle_http_error)
            app.add_error_handler(Exception, custom_handle_uncaught_exception)
            app.add_error_handler(falcon.HTTPNotFound, custom_handle_404)

        If an instance of ``falcon.HTTPForbidden`` is raised, it will be
        handled by ``custom_handle_http_error()``. ``falcon.HTTPError`` is a
        superclass of ``falcon.HTTPForbidden`` and a subclass of ``Exception``,
        so it is the most specific exception type with a registered handler.

        If an instance of ``falcon.HTTPNotFound`` is raised, it will be handled
        by ``custom_handle_404()``, not by ``custom_handle_not_found()``, because
        ``custom_handle_404()`` was registered more recently.

        .. Note::

            By default, the framework installs three handlers, one for
            :class:`~.HTTPError`, one for :class:`~.HTTPStatus`, and one for
            the standard ``Exception`` type, which prevents passing uncaught
            exceptions to the WSGI server. These can be overridden by adding a
            custom error handler method for the exception type in question.

        Args:
            exception (type or iterable of types): When handling a request,
                whenever an error occurs that is an instance of the specified
                type(s), the associated handler will be called. Either a single
                type or an iterable of types may be specified.
            handler (callable): A coroutine function taking the form
                ``async func(req, resp, ex, params)``.

                If not specified explicitly, the handler will default to
                ``exception.handle``, where ``exception`` is the error
                type specified above, and ``handle`` is a static method
                (i.e., decorated with ``@staticmethod``) that accepts
                the same params just described. For example::

                    class CustomException(CustomBaseException):

                        @staticmethod
                        async def handle(req, resp, ex, params):
                            # TODO: Log the error
                            # Convert to an instance of falcon.HTTPError
                            raise falcon.HTTPError(falcon.HTTP_792)

                If an iterable of exception types is specified instead of
                a single type, the handler must be explicitly specified.
        """

        if handler is None:
            try:
                handler = exception.handle
            except AttributeError:
                raise AttributeError('handler must either be specified '
                                     'explicitly or defined as a static'
                                     'method named "handle" that is a '
                                     'member of the given exception class.')

        handler = _wrap_non_coroutine_unsafe(handler)

        # NOTE(kgriffs): iscoroutinefunction() always returns False
        #   for cythonized functions.
        #
        #   https://github.com/cython/cython/issues/2273
        #   https://bugs.python.org/issue38225
        #
        if not iscoroutinefunction(handler) and is_python_func(handler):
            raise CompatibilityError(
                'The handler must be an awaitable coroutine function in order '
                'to be used safely with an ASGI app.')

        try:
            exception_tuple = tuple(exception)
        except TypeError:
            exception_tuple = (exception, )

        for exc in exception_tuple:
            if not issubclass(exc, BaseException):
                raise TypeError('"exception" must be an exception type.')

            self._error_handlers[exc] = handler
Esempio n. 5
0
    def add_error_handler(self, exception, handler=None):
        """Register a handler for one or more exception types.

        Error handlers may be registered for any exception type, including
        :class:`~.HTTPError` or :class:`~.HTTPStatus`. This feature
        provides a central location for logging and otherwise handling
        exceptions raised by responders, hooks, and middleware components.

        A handler can raise an instance of :class:`~.HTTPError` or
        :class:`~.HTTPStatus` to communicate information about the issue to
        the client.  Alternatively, a handler may modify `resp`
        directly.

        An error handler "matches" a raised exception if the exception is an
        instance of the corresponding exception type. If more than one error
        handler matches the raised exception, the framework will choose the
        most specific one, as determined by the method resolution order of the
        raised exception type. If multiple error handlers are registered for the
        *same* exception class, then the most recently-registered handler is
        used.

        For example, suppose we register error handlers as follows::

            app = App()
            app.add_error_handler(falcon.HTTPNotFound, custom_handle_not_found)
            app.add_error_handler(falcon.HTTPError, custom_handle_http_error)
            app.add_error_handler(Exception, custom_handle_uncaught_exception)
            app.add_error_handler(falcon.HTTPNotFound, custom_handle_404)

        If an instance of ``falcon.HTTPForbidden`` is raised, it will be
        handled by ``custom_handle_http_error()``. ``falcon.HTTPError`` is a
        superclass of ``falcon.HTTPForbidden`` and a subclass of ``Exception``,
        so it is the most specific exception type with a registered handler.

        If an instance of ``falcon.HTTPNotFound`` is raised, it will be handled
        by ``custom_handle_404()``, not by ``custom_handle_not_found()``, because
        ``custom_handle_404()`` was registered more recently.

        Note:

            By default, the framework installs three handlers, one for
            :class:`~.HTTPError`, one for :class:`~.HTTPStatus`, and one for
            the standard ``Exception`` type, which prevents passing uncaught
            exceptions to the WSGI server. These can be overridden by adding a
            custom error handler method for the exception type in question.

            When a generic unhandled exception is raised while
            handling a :ref:`WebSocket <ws>` connection, the default handler will
            close the connection with the standard close code ``1011`` (Internal
            Error). If your ASGI server does not support this code, the
            framework will use code ``3011`` instead; or you can customize
            it via the
            :attr:`~falcon.asgi.WebSocketOptions.error_close_code`
            property of :attr:`~.ws_options`.

            On the other hand, if an ``on_websocket()`` responder raises an
            instance of :class:`~falcon.HTTPError`, the default error handler
            will close the :ref:`WebSocket <ws>` connection with a framework
            close code derived by adding ``3000`` to the HTTP status code (e.g.,
            ``3404``)

        Args:
            exception (type or iterable of types): When handling a request,
                whenever an error occurs that is an instance of the specified
                type(s), the associated handler will be called. Either a single
                type or an iterable of types may be specified.

        Keyword Args:
            handler (callable): A coroutine function taking the
                form::

                    async def func(req, resp, ex, params, ws=None):
                        pass

                In the case of a WebSocket connection, the `resp` argument
                will be ``None``, while the `ws` keyword argument
                will receive the :class:`~falcon.asgi.WebSocket` object
                representing the connection.

                If the `handler` keyword argument is not provided to
                :meth:`~.add_error_handler`, the handler will default to
                ``exception.handle``, where ``exception`` is the error type
                specified above, and ``handle`` is a static method (i.e.,
                decorated with ``@staticmethod``) that accepts the params
                just described. For example::

                    class CustomException(CustomBaseException):

                        @staticmethod
                        async def handle(req, resp, ex, params):
                            # TODO: Log the error
                            # Convert to an instance of falcon.HTTPError
                            raise falcon.HTTPError(falcon.HTTP_792)

                Note, however, that if an iterable of exception types is
                specified instead of a single type, the handler must be
                explicitly specified using the `handler` keyword argument.
        """

        if handler is None:
            try:
                handler = exception.handle
            except AttributeError:
                raise AttributeError('handler must either be specified '
                                     'explicitly or defined as a static'
                                     'method named "handle" that is a '
                                     'member of the given exception class.')

        # NOTE(vytas): Do not shoot ourselves in the foot in case error
        #   handlers are our own cythonized code.
        if handler not in (
                self._http_status_handler,
                self._http_error_handler,
                self._python_error_handler,
        ):
            handler = _wrap_non_coroutine_unsafe(handler)

        # NOTE(kgriffs): iscoroutinefunction() always returns False
        #   for cythonized functions.
        #
        #   https://github.com/cython/cython/issues/2273
        #   https://bugs.python.org/issue38225
        #
        if not iscoroutinefunction(handler) and is_python_func(handler):
            raise CompatibilityError(
                'The handler must be an awaitable coroutine function in order '
                'to be used safely with an ASGI app.')

        try:
            exception_tuple = tuple(exception)
        except TypeError:
            exception_tuple = (exception, )

        for exc in exception_tuple:
            if not issubclass(exc, BaseException):
                raise TypeError('"exception" must be an exception type.')

            self._error_handlers[exc] = handler
Esempio n. 6
0
def prepare_middleware(middleware, independent_middleware=False, asgi=False):
    """Check middleware interfaces and prepare the methods for request handling.

    Arguments:
        middleware (iterable): An iterable of middleware objects.

    Keyword Args:
        independent_middleware (bool): ``True`` if the request and
            response middleware methods should be treated independently
            (default ``False``)
        asgi (bool): ``True`` if an ASGI app, ``False`` otherwise
            (default ``False``)

    Returns:
        tuple: A tuple of prepared middleware method tuples
    """

    # PERF(kgriffs): do getattr calls once, in advance, so we don't
    # have to do them every time in the request path.
    request_mw = []
    resource_mw = []
    response_mw = []

    for component in middleware:
        # NOTE(kgriffs): Middleware that uses parts of the Request and Response
        #   interfaces that are the same between ASGI and WSGI (most of it is,
        #   and we should probably define this via ABC) can just implement
        #   the method names without the *_async postfix. If a middleware
        #   component wants to provide an alternative implementation that
        #   does some work that requires async def, or something specific about
        #   the ASGI Request/Response classes, the component can implement the
        #   *_async method in that case.
        #
        #   Middleware that is WSGI-only or ASGI-only can simply implement all
        #   methods without the *_async postfix. Regardless, components should
        #   clearly document their compatibility with WSGI vs. ASGI.

        if asgi:
            process_request = (
                util.get_bound_method(component, 'process_request_async') or
                _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_request')
                )
            )

            process_resource = (
                util.get_bound_method(component, 'process_resource_async') or
                _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_resource')
                )
            )

            process_response = (
                util.get_bound_method(component, 'process_response_async') or
                _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_response')
                )
            )

            for m in (process_request, process_resource, process_response):
                if m and not iscoroutinefunction(m):
                    msg = (
                        '{} must be implemented as an awaitable coroutine. If '
                        'you would like to retain compatibility '
                        'with WSGI apps, the coroutine versions of the '
                        'middleware methods may be implemented side-by-side '
                        'by applying an *_async postfix to the method names. '
                    )
                    raise CompatibilityError(msg.format(m))

        else:
            process_request = util.get_bound_method(component, 'process_request')
            process_resource = util.get_bound_method(component, 'process_resource')
            process_response = util.get_bound_method(component, 'process_response')

            for m in (process_request, process_resource, process_response):
                if m and iscoroutinefunction(m):
                    msg = (
                        '{} may not implement coroutine methods and '
                        'remain compatible with WSGI apps without '
                        'using the *_async postfix to explicitly identify '
                        'the coroutine version of a given middleware '
                        'method.'
                    )
                    raise CompatibilityError(msg.format(component))

        if not (process_request or process_resource or process_response):
            if asgi and (
                hasattr(component, 'process_startup') or hasattr(component, 'process_shutdown')
            ):
                # NOTE(kgriffs): This middleware only has ASGI lifespan
                #   event handlers
                continue

            msg = '{0} must implement at least one middleware method'
            raise TypeError(msg.format(component))

        # NOTE: depending on whether we want to execute middleware
        # independently, we group response and request middleware either
        # together or separately.
        if independent_middleware:
            if process_request:
                request_mw.append(process_request)
            if process_response:
                response_mw.insert(0, process_response)
        else:
            if process_request or process_response:
                request_mw.append((process_request, process_response))

        if process_resource:
            resource_mw.append(process_resource)

    return (tuple(request_mw), tuple(resource_mw), tuple(response_mw))
Esempio n. 7
0
def prepare_middleware(middleware, independent_middleware=False, asgi=False):
    """Check middleware interfaces and prepare the methods for request handling.

    Arguments:
        middleware (iterable): An iterable of middleware objects.

    Keyword Args:
        independent_middleware (bool): ``True`` if the request and
            response middleware methods should be treated independently
            (default ``False``)
        asgi (bool): ``True`` if an ASGI app, ``False`` otherwise
            (default ``False``)

    Returns:
        tuple: A tuple of prepared middleware method tuples
    """

    # PERF(kgriffs): do getattr calls once, in advance, so we don't
    # have to do them every time in the request path.
    request_mw = []
    resource_mw = []
    response_mw = []

    for component in middleware:
        # NOTE(kgriffs): Middleware that supports both WSGI and ASGI can
        #   append an *_async postfix to the ASGI version of the method
        #   to distinguish the two. Otherwise, the prefix is unnecessary.

        if asgi:
            process_request = (
                util.get_bound_method(component, 'process_request_async')
                or _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_request')))

            process_resource = (
                util.get_bound_method(component, 'process_resource_async')
                or _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_resource')))

            process_response = (
                util.get_bound_method(component, 'process_response_async')
                or _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_response')))

            for m in (process_request, process_resource, process_response):
                # NOTE(kgriffs): iscoroutinefunction() always returns False
                #   for cythonized functions.
                #
                #   https://github.com/cython/cython/issues/2273
                #   https://bugs.python.org/issue38225
                #
                if m and not iscoroutinefunction(m) and util.is_python_func(m):
                    msg = (
                        '{} must be implemented as an awaitable coroutine. If '
                        'you would like to retain compatibility '
                        'with WSGI apps, the coroutine versions of the '
                        'middleware methods may be implemented side-by-side '
                        'by applying an *_async postfix to the method names. ')
                    raise CompatibilityError(msg.format(m))

        else:
            process_request = util.get_bound_method(component,
                                                    'process_request')
            process_resource = util.get_bound_method(component,
                                                     'process_resource')
            process_response = util.get_bound_method(component,
                                                     'process_response')

            for m in (process_request, process_resource, process_response):
                if m and iscoroutinefunction(m):
                    msg = ('{} may not implement coroutine methods and '
                           'remain compatible with WSGI apps without '
                           'using the *_async postfix to explicitly identify '
                           'the coroutine version of a given middleware '
                           'method.')
                    raise CompatibilityError(msg.format(component))

        if not (process_request or process_resource or process_response):
            if asgi and (hasattr(component, 'process_startup')
                         or hasattr(component, 'process_shutdown')):
                # NOTE(kgriffs): This middleware only has ASGI lifespan
                #   event handlers
                continue

            msg = '{0} must implement at least one middleware method'
            raise TypeError(msg.format(component))

        # NOTE: depending on whether we want to execute middleware
        # independently, we group response and request middleware either
        # together or separately.
        if independent_middleware:
            if process_request:
                request_mw.append(process_request)
            if process_response:
                response_mw.insert(0, process_response)
        else:
            if process_request or process_response:
                request_mw.append((process_request, process_response))

        if process_resource:
            resource_mw.append(process_resource)

    return (tuple(request_mw), tuple(resource_mw), tuple(response_mw))