Example #1
0
    def invoke_request(self, request,
                       _use_tweens=True, _apply_extensions=False):
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)

        if _use_tweens:
            handle_request = self.handle_request
        else:
            handle_request = self.orig_handle_request

        try:

            try:
                extensions = self.request_extensions
                if _apply_extensions and extensions is not None:
                    apply_request_extensions(request, extensions=extensions)
                response = handle_request(request)

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                has_listeners and notify(NewResponse(request, response))

                return response

            finally:
                if request.finished_callbacks:
                    request._process_finished_callbacks()

        finally:
            manager.pop()
Example #2
0
    def invoke_request(self, request, _use_tweens=True):
        """
        Execute a request through the request processing pipeline and
        return the generated response.

        """
        registry = self.registry
        has_listeners = registry.has_listeners
        notify = registry.notify

        if _use_tweens:
            handle_request = self.handle_request
        else:
            handle_request = self.orig_handle_request

        try:
            response = handle_request(request)

            if request.response_callbacks:
                request._process_response_callbacks(response)

            has_listeners and notify(NewResponse(request, response))

            return response

        finally:
            if request.finished_callbacks:
                request._process_finished_callbacks()
Example #3
0
    def __call__(self, environ, start_response):
        """
        Accept ``environ`` and ``start_response``; create a
        :term:`request` and route the request to a :app:`Pyramid`
        view based on introspection of :term:`view configuration`
        within the application registry; call ``start_response`` and
        return an iterable.
        """
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        request = self.request_factory(environ)
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)
        request.registry = registry
        try:

            try:
                response = self.handle_request(request)
                has_listeners and notify(NewResponse(request, response))

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                return response(request.environ, start_response)

            finally:
                if request.finished_callbacks:
                    request._process_finished_callbacks()

        finally:
            manager.pop()
Example #4
0
    def invoke_subrequest(self, request, use_tweens=False):
        """Obtain a response object from the Pyramid application based on
        information in the ``request`` object provided.  The ``request``
        object must be an object that implements the Pyramid request
        interface (such as a :class:`pyramid.request.Request` instance).  If
        ``use_tweens`` is ``True``, the request will be sent to the
        :term:`tween` in the tween stack closest to the request ingress.  If
        ``use_tweens`` is ``False``, the request will be sent to the main
        router handler, and no tweens will be invoked.
        
        See the API for pyramid.request for complete documentation.
        """
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)
        request.registry = registry
        request.invoke_subrequest = self.invoke_subrequest

        if use_tweens:
            handle_request = self.handle_request
        else:
            handle_request = self.orig_handle_request

        try:

            try:
                extensions = self.request_extensions
                if extensions is not None:
                    request._set_extensions(extensions)
                response = handle_request(request)

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                has_listeners and notify(NewResponse(request, response))

                return response

            finally:
                if request.finished_callbacks:
                    request._process_finished_callbacks()

        finally:
            manager.pop()
Example #5
0
    def invoke_request(self, request, _use_tweens=True):
        """
        Execute a request through the request processing pipeline and
        return the generated response.

        """
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)

        if _use_tweens:
            handle_request = self.handle_request
        else:
            handle_request = self.orig_handle_request

        try:

            try:
                response = handle_request(request)

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                has_listeners and notify(NewResponse(request, response))

                return response

            finally:
                if request.finished_callbacks:
                    request._process_finished_callbacks()

        finally:
            manager.pop()
Example #6
0
    def invoke_subrequest(self, existing_request, path):
        """
        pulled out of pyramid(backport)
        """
        # create a new environ object copied from the original
        # so we can auth, etc
        request = Request.blank(path)
        for key in [
                'AUTH_TYPE', 'REMOTE_USER_TOKENS', 'repoze.browserid',
                'HTTP_COOKIE', 'karl.identity', 'paste.cookies',
                'webob._parsed_cookies'
        ]:
            request.environ[key] = existing_request.environ.get(key)
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)
        request.registry = registry
        request.invoke_subrequest = self.invoke_subrequest

        try:
            try:
                response = self.handle_request(request)

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                has_listeners and notify(NewResponse(request, response))
                return response
            finally:
                if request.finished_callbacks:
                    request._process_finished_callbacks()
        finally:
            manager.pop()
Example #7
0
    def invoke_subrequest(self, request, use_tweens=False):
        """
        Obtain a response object from the Pyramid application based on
        information in the ``request`` object provided.  The ``request``
        object must be an object that implements the Pyramid request
        interface (such as a :class:`pyramid.request.Request` instance).  If
        ``use_tweens`` is ``True``, the request will be sent to the
        :term:`tween` in the tween stack closest to the request ingress.  If
        ``use_tweens`` is ``False``, the request will be sent to the main
        router handler, and no tweens will be invoked.  This function also:
        
        - manages the threadlocal stack (so that
          :func:`~pyramid.threadlocal.get_current_request` and
          :func:`~pyramid.threadlocal.get_current_registry` work during a
          request)

        - Adds a ``registry`` attribute and a ``invoke_subrequest`` attribute
          (a callable) to the request object it's handed.

        - sets request extensions (such as those added via
          :meth:`~pyramid.config.Configurator.add_request_method` or
          :meth:`~pyramid.config.Configurator.set_request_property`) on the
          request it's passed.

        - causes a :class:`~pyramid.event.NewRequest` event to be sent at the
          beginning of request processing.

        - causes a :class:`~pyramid.event.ContextFound` event to be sent
          when a context resource is found.
          
        - Calls any :term:`response callback` functions defined within the
          request's lifetime if a response is obtained from the Pyramid
          application.

        - causes a :class:`~pyramid.event.NewResponse` event to be sent if a
          response is obtained.

        - Calls any :term:`finished callback` functions defined within the
          request's lifetime.

        See also :ref:`subrequest_chapter`.
        """
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)
        request.registry = registry
        request.invoke_subrequest = self.invoke_subrequest

        if use_tweens:
            handle_request = self.handle_request
        else:
            handle_request = self.orig_handle_request

        try:

            try:
                extensions = self.request_extensions
                if extensions is not None:
                    request._set_extensions(extensions)
                response = handle_request(request)

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                has_listeners and notify(NewResponse(request, response))

                return response

            finally:
                if request.finished_callbacks:
                    request._process_finished_callbacks()

        finally:
            manager.pop()
Example #8
0
    def invoke_subrequest(self, request, use_tweens=False):
        """Obtain a response object from the Pyramid application based on
        information in the ``request`` object provided.  The ``request``
        object must be an object that implements the Pyramid request
        interface (such as a :class:`pyramid.request.Request` instance).  If
        ``use_tweens`` is ``True``, the request will be sent to the
        :term:`tween` in the tween stack closest to the request ingress.  If
        ``use_tweens`` is ``False``, the request will be sent to the main
        router handler, and no tweens will be invoked.

        See the API for pyramid.request for complete documentation.
        """
        registry = self.registry
        has_listeners = self.registry.has_listeners
        notify = self.registry.notify
        threadlocals = {'registry': registry, 'request': request}
        manager = self.threadlocal_manager
        manager.push(threadlocals)
        request.registry = registry
        request.invoke_subrequest = self.invoke_subrequest

        if use_tweens:
            # XXX Recopy tweens state, registered my own ITweens does not
            # save the registred handler. Should invest more
            tween = Tweens()
            registred_tweens = registry.queryUtility(ITweens)
            if registred_tweens is not None:
                tween.explicit = registred_tweens.explicit
                tween.implicit = registred_tweens.implicit
                handle_request = tween(self.orig_handle_request, registry)
            else:
                handle_request = self.orig_handle_request
        else:
            handle_request = self.orig_handle_request

        try:

            try:
                extensions = self.request_extensions
                if extensions is not None:
                    request._set_extensions(extensions)

                response = yield from handle_request(request)

                if request.response_callbacks:
                    yield from request._process_response_callbacks(response)

                has_listeners and notify(NewResponse(request, response))

            # XXX excview_tween_factory is not a generator
            # Move a part of its code here
            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 = request.__dict__
                attrs['exc_info'] = sys.exc_info()
                attrs['exception'] = exc
                adapters = request.registry.adapters

                # 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)
                for_ = (IExceptionViewClassifier, request_iface.combined,
                        provides)
                view_callable = adapters.lookup(for_, IView, default=None)
                if view_callable is None:
                    raise
                response = view_callable(exc, request)
                while is_generator(response):
                    response = yield from response

            finally:
                if request.finished_callbacks:
                    yield from request._process_finished_callbacks()

        finally:
            manager.pop()

        return response
Example #9
0
    def __call__(self, environ, start_response):
        """
        Accept ``environ`` and ``start_response``; create a
        :term:`request` and route the request to a :app:`Pyramid`
        view based on introspection of :term:`view configuration`
        within the application registry; call ``start_response`` and
        return an iterable.
        """
        registry = self.registry
        adapters = registry.adapters
        has_listeners = registry.has_listeners
        logger = self.logger
        manager = self.threadlocal_manager
        request = None
        threadlocals = {'registry': registry, 'request': request}
        manager.push(threadlocals)

        try:  # matches finally: manager.pop()

            try:  # matches finally:  ... call request finished callbacks ...

                # create the request
                request = self.request_factory(environ)
                context = None
                threadlocals['request'] = request
                attrs = request.__dict__
                attrs['registry'] = registry
                request_iface = IRequest

                try:  # matches except Exception (exception view execution)
                    has_listeners and registry.notify(NewRequest(request))
                    # find the root object
                    root_factory = self.root_factory
                    if self.routes_mapper is not None:
                        info = self.routes_mapper(request)
                        match, route = info['match'], info['route']
                        if route is None:
                            if self.debug_routematch:
                                msg = ('no route matched for url %s' %
                                       request.url)
                                logger and logger.debug(msg)
                        else:
                            # TODO: kill off bfg.routes.* environ keys when
                            # traverser requires request arg, and cant cope
                            # with environ anymore (they are docs-deprecated as
                            # of BFG 1.3)
                            environ['bfg.routes.route'] = route
                            environ['bfg.routes.matchdict'] = match
                            attrs['matchdict'] = match
                            attrs['matched_route'] = route

                            if self.debug_routematch:
                                msg = ('route matched for url %s; '
                                       'route_name: %r, '
                                       'path_info: %r, '
                                       'pattern: %r, '
                                       'matchdict: %r, '
                                       'predicates: %r' %
                                       (request.url, route.name,
                                        request.path_info, route.pattern,
                                        match, route.predicates))
                                logger and logger.debug(msg)

                            request_iface = registry.queryUtility(
                                IRouteRequest,
                                name=route.name,
                                default=IRequest)
                            root_factory = route.factory or self.root_factory

                    root = root_factory(request)
                    attrs['root'] = root

                    # find a context
                    traverser = adapters.queryAdapter(root, ITraverser)
                    if traverser is None:
                        traverser = ResourceTreeTraverser(root)
                    tdict = traverser(request)
                    context, view_name, subpath, traversed, vroot, vroot_path = (
                        tdict['context'], tdict['view_name'], tdict['subpath'],
                        tdict['traversed'], tdict['virtual_root'],
                        tdict['virtual_root_path'])
                    attrs.update(tdict)
                    has_listeners and registry.notify(ContextFound(request))

                    # find a view callable
                    context_iface = providedBy(context)
                    view_callable = adapters.lookup(
                        (IViewClassifier, request_iface, context_iface),
                        IView,
                        name=view_name,
                        default=None)

                    # invoke the view callable
                    if view_callable is None:
                        if self.debug_notfound:
                            msg = ('debug_notfound of url %s; path_info: %r, '
                                   'context: %r, view_name: %r, subpath: %r, '
                                   'traversed: %r, root: %r, vroot: %r, '
                                   'vroot_path: %r' %
                                   (request.url, request.path_info, context,
                                    view_name, subpath, traversed, root, vroot,
                                    vroot_path))
                            logger and logger.debug(msg)
                        else:
                            msg = request.path_info
                        raise NotFound(msg)
                    else:
                        response = view_callable(context, request)

                # handle exceptions raised during root finding and view-exec
                except Exception, why:
                    attrs['exception'] = why

                    for_ = (IExceptionViewClassifier, request_iface.combined,
                            providedBy(why))
                    view_callable = adapters.lookup(for_, IView, default=None)

                    if view_callable is None:
                        raise

                    try:
                        msg = why[0]
                    except:
                        msg = ''

                    # repoze.bfg.message docs-deprecated in Pyramid 1.0
                    environ['repoze.bfg.message'] = msg

                    response = view_callable(why, request)

                # process the response

                has_listeners and registry.notify(
                    NewResponse(request, response))

                if request.response_callbacks:
                    request._process_response_callbacks(response)

                try:
                    headers = response.headerlist
                    app_iter = response.app_iter
                    status = response.status
                except AttributeError:
                    raise ValueError(
                        'Non-response object returned from view named %s '
                        '(and no renderer): %r' % (view_name, response))

            finally:
                if request is not None and request.finished_callbacks:
                    request._process_finished_callbacks()

            start_response(status, headers)
            return app_iter
 def test_xrds_header(self):
     event = NewResponse(self.request, self.request.response)
     add_yadis_header(event)
     self.assertIn(YADIS_HEADER_NAME, event.response.headers)