Esempio n. 1
0
 def test_instance_implements(self):
     from zope.interface.verify import verifyObject
     from pyramid.events import ContextFound
     from pyramid.interfaces import IContextFound
     request = DummyRequest()
     inst = ContextFound(request)
     verifyObject(IContextFound, inst)
Esempio n. 2
0
def get_env(config_uri, base_url):
    """
    Return a preconfigured paste environment object. Sets up the WSGI
    application and ensures that webassets knows to load files from
    ``h:static`` regardless of the ``webassets.base_dir`` setting.
    """
    request = Request.blank('', base_url=base_url)
    env = paster.bootstrap(config_uri, request)
    request.root = env['root']

    # Ensure that the webassets URL is absolute
    request.webassets_env.url = urlparse.urljoin(base_url,
                                                 request.webassets_env.url)

    # Disable webassets caching and manifest generation
    request.webassets_env.cache = False
    request.webassets_env.manifest = False

    # By default, webassets will use its base_dir setting as its search path.
    # When building extensions, we change base_dir so as to build assets
    # directly into the extension directories. As a result, we have to add
    # back the correct search path.
    request.webassets_env.append_path(
        resolve('h:static').abspath(), request.webassets_env.url)

    request.registry.notify(ContextFound(request))  # pyramid_layout attrs

    return env
def context_found_event(app_request, app_context, app_registry_mock):
    app_request.registry = app_registry_mock
    app_request.context = app_context
    event = MagicMock(wraps=ContextFound(app_request),
                      name='context_found_event')
    # type-wide property mock, okay for request of course
    type(event).request = PropertyMock(return_value=app_request)
    return event
Esempio n. 4
0
File: script.py Progetto: Treora/h
def build_extension(env, browser, content_dir):
    registry = env['registry']
    request = env['request']
    request.root = env['root']
    context = request.context

    registry.notify(ContextFound(request))  # pyramid_layout attrs
    request.layout_manager.layout.csp = ''

    # Remove any existing build
    if exists('./build/' + browser):
        rmtree('./build/' + browser)

    # Create the new build directory
    makedirs(content_dir)

    # Change to the output directory
    old_dir = getcwd()
    chdir('./build/' + browser)

    # Copy the extension code
    merge('../../h/browser/' + browser, './')

    # Copy over the config and destroy scripts
    copyfile('../../h/static/extension/destroy.js',
             content_dir + '/destroy.js')
    copyfile('../../h/static/extension/config.js', content_dir + '/config.js')

    # Build the app html and copy assets if they are being bundled
    if (request.webassets_env.url.startswith('chrome-extension://')
            or request.webassets_env.url.startswith('resource://')):
        merge('../../h/static/images', content_dir + '/images')

        # Copy over the vendor assets since they won't be processed otherwise
        if request.webassets_env.debug:
            makedirs(content_dir + '/scripts/vendor')
            merge('../../h/static/scripts/vendor',
                  content_dir + '/scripts/vendor')

        app(content_dir + '/app.html', context, request)

    if browser == 'chrome':
        chrome_manifest(context, request)
        remove('./karma.config.js')
        rmtree('./test/')
    elif browser == 'firefox':
        firefox_manifest(context, request)

    embed(content_dir + '/embed.js', context, request)

    # Reset the directory
    chdir(old_dir)
Esempio n. 5
0
def chrome(env):
    registry = env['registry']
    settings = registry.settings

    request = env['request']
    context = request.context

    registry.notify(ContextFound(request))  # pyramid_layout attrs
    request.layout_manager.layout.csp = ''

    manifest(context, request)
    embed(context, request)

    if asbool(settings.get('webassets.debug', False)) is False:
        app(context, request)
def test_entity_form_view(app_request, app_context, entity_form_view,
                          webapp_settings, jinja2_env, entry_point_mock):
    # code smell - would come from "context found."
    # we miss everything that comes from context found ...

    #app_context.template_env = jinja2_env
    # function to set these thingers?
    app_request.context = app_context
    on_context_found(ContextFound(app_request))

    view = entity_form_view()
    dump_mock_calls(entry_point_mock, entry_point_mock.mock_calls)
    #_dump(entry_point_mock.mock_calls, cb=lambda fmt, *args: print(fmt % args, file=sys.stderr), line_prefix='calls: ')
    # entry_point_mock.assert_has_calls([
    #     call.init_generator()
    # ])
    assert view
Esempio n. 7
0
def setup_commandline_pyramid(configfile):

    # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/commandline.html#writing-a-script
    # https://stackoverflow.com/questions/6206556/running-scripts-within-pyramid-framework-ie-without-a-server
    # https://stackoverflow.com/questions/12510133/share-pyramid-configuration-with-a-cli-script

    # Setup logging, manually
    logging.config.fileConfig(configfile)
    logger.setLevel(logging.DEBUG)

    # Bootstrap a Pyramid script
    # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/commandline.html#writing-a-script
    env = bootstrap(configfile)

    # Get request and registry objects from environment
    request = env['request']
    registry = env['registry']

    # Run event subscriptions to attach data source client pool objects to request object
    event = ContextFound(request)
    registry.notify(event)

    return env
Esempio n. 8
0
    def handle_request(self, request):
        attrs = request.__dict__
        registry = attrs['registry']

        request.request_iface = IRequest
        context = None
        routes_mapper = self.routes_mapper
        debug_routematch = self.debug_routematch
        adapters = registry.adapters
        has_listeners = registry.has_listeners
        notify = registry.notify
        logger = self.logger

        has_listeners and notify(NewRequest(request))
        # find the root object
        root_factory = self.root_factory
        if routes_mapper is not None:
            info = routes_mapper(request)
            match, route = info['match'], info['route']
            if route is None:
                if debug_routematch:
                    msg = ('no route matched for url %s' % request.url)
                    logger and logger.debug(msg)
            else:
                attrs['matchdict'] = match
                attrs['matched_route'] = route

                if 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, ', '.join(
                                [p.text() for p in route.predicates])))
                    logger and logger.debug(msg)

                request.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 notify(ContextFound(request))

        # find a view callable
        context_iface = providedBy(context)
        view_callable = adapters.lookup(
            (IViewClassifier, request.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 HTTPNotFound(msg)
        else:
            try:
                response = view_callable(context, request)
            except PredicateMismatch:
                # look for other views that meet the predicate
                # criteria
                for iface in context_iface.__sro__[1:]:
                    previous_view_callable = view_callable
                    view_callable = adapters.lookup(
                        (IViewClassifier, request.request_iface, iface),
                        IView,
                        name=view_name,
                        default=None)
                    # intermediate bases may lookup same view_callable
                    if view_callable is previous_view_callable:
                        continue
                    if view_callable is not None:
                        try:
                            response = view_callable(context, request)
                            break
                        except PredicateMismatch:
                            pass
                else:
                    raise
        return response
Esempio n. 9
0
    def handle_request(self, request):
        attrs = request.__dict__
        registry = attrs['registry']

        request.request_iface = IRequest
        context = None
        routes_mapper = self.routes_mapper
        debug_routematch = self.debug_routematch
        adapters = registry.adapters
        has_listeners = registry.has_listeners
        notify = registry.notify
        logger = self.logger

        has_listeners and notify(NewRequest(request))
        # find the root object
        root_factory = self.root_factory
        if routes_mapper is not None:
            info = routes_mapper(request)
            match, route = info['match'], info['route']
            if route is None:
                if debug_routematch:
                    msg = 'no route matched for url %s' % request.url
                    logger and logger.debug(msg)
            else:
                attrs['matchdict'] = match
                attrs['matched_route'] = route

                if 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,
                               ', '.join([p.text() for p in route.predicates]),
                           ))
                    logger and logger.debug(msg)

                request.request_iface = registry.queryUtility(IRouteRequest,
                                                              name=route.name,
                                                              default=IRequest)

                root_factory = route.factory or self.root_factory

        # Notify anyone listening that we are about to start traversal
        #
        # Notify before creating root_factory in case we want to do something
        # special on a route we may have matched. See
        # https://github.com/Pylons/pyramid/pull/1876 for ideas of what is
        # possible.
        has_listeners and notify(BeforeTraversal(request))

        # Create the root factory
        root = root_factory(request)
        attrs['root'] = root

        # We are about to traverse and 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)

        # Notify anyone listening that we have a context and traversal is
        # complete
        has_listeners and notify(ContextFound(request))

        # find a view callable
        context_iface = providedBy(context)
        response = _call_view(registry, request, context, context_iface,
                              view_name)

        if response 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 HTTPNotFound(msg)

        return response
Esempio n. 10
0
def notfound(context, request):
    # Dispatch ContextFound for pyramid_layout subscriber
    event = ContextFound(request)
    request.context = context
    request.registry.notify(event)
    return {}
Esempio n. 11
0
    def handle_request(self, request):
        attrs = request.__dict__
        registry = attrs['registry']

        request.request_iface = IRequest
        context = None
        routes_mapper = self.routes_mapper
        debug_routematch = self.debug_routematch
        adapters = registry.adapters
        has_listeners = registry.has_listeners
        notify = registry.notify
        logger = self.logger

        has_listeners and notify(NewRequest(request))
        # find the root object
        root_factory = self.root_factory
        if routes_mapper is not None:
            info = routes_mapper(request)
            match, route = info['match'], info['route']
            if route is None:
                if 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 = request.environ
                environ['bfg.routes.route'] = route
                environ['bfg.routes.matchdict'] = match
                attrs['matchdict'] = match
                attrs['matched_route'] = route

                if 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, ', '.join(
                                [p.__text__ for p in route.predicates])))
                    logger and logger.debug(msg)

                request.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 notify(ContextFound(request))

        # find a view callable
        context_iface = providedBy(context)
        view_callable = adapters.lookup(
            (IViewClassifier, request.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 HTTPNotFound(msg)
        else:
            response = view_callable(context, request)

        return response
Esempio n. 12
0
def adjust(request):
    notify(ContextFound(request))
Esempio n. 13
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
Esempio n. 14
0
    def handle_request(self, request):
        attrs = request.__dict__
        registry = attrs['registry']

        request.request_iface = IRequest
        context = None
        routes_mapper = self.routes_mapper
        debug_routematch = self.debug_routematch
        adapters = registry.adapters
        has_listeners = registry.has_listeners
        notify = registry.notify
        logger = self.logger

        has_listeners and notify(NewRequest(request))
        # find the root object
        root_factory = self.root_factory
        if routes_mapper is not None:
            info = routes_mapper(request)
            match, route = info['match'], info['route']
            if route is None:
                if debug_routematch:
                    msg = ('no route matched for url %s' % request.url)
                    logger and logger.debug(msg)
            else:
                attrs['matchdict'] = match
                attrs['matched_route'] = route

                if 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, ', '.join(
                                [p.text() for p in route.predicates])))
                    logger and logger.debug(msg)

                request.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 notify(ContextFound(request))

        # find a view callable
        context_iface = providedBy(context)
        response = _call_view(registry, request, context, context_iface,
                              view_name)

        if response 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 HTTPNotFound(msg)

        return response
def adjust(request):
    _adjust(ContextFound(request))