示例#1
0
 def run(self):
     if len(self.args) < 2:
         self.out("Command requires a config file arg and a url arg")
         return 2
     config_uri, url = self.args
     if not url.startswith("/"):
         url = "/%s" % url
     env = self.bootstrap[0](config_uri)
     registry = env["registry"]
     view = self._find_view(url, registry)
     self.out("")
     self.out("URL = %s" % url)
     self.out("")
     if view is not None:
         self.out("    context: %s" % view.__request_attrs__["context"])
         self.out("    view name: %s" % view.__request_attrs__["view_name"])
     if IMultiView.providedBy(view):
         for dummy, view_wrapper, dummy in view.views:
             self.output_view_info(view_wrapper)
             if IMultiView.providedBy(view_wrapper):
                 for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                     self.output_view_info(mv_view_wrapper, level=2)
     else:
         if view is not None:
             self.output_view_info(view)
         else:
             self.out("    Not found.")
     self.out("")
     return 0
示例#2
0
 def command(self):
     config_uri, url = self.args
     if not url.startswith('/'):
         url = '/%s' % url
     env = self.bootstrap[0](config_uri)
     registry = env['registry']
     view = self._find_view(url, registry)
     self.out('')
     self.out("URL = %s" % url)
     self.out('')
     if view is not None:
         self.out("    context: %s" % view.__request_attrs__['context'])
         self.out("    view name: %s" % view.__request_attrs__['view_name'])
     if IMultiView.providedBy(view):
         for dummy, view_wrapper, dummy in view.views:
             self.output_view_info(view_wrapper)
             if IMultiView.providedBy(view_wrapper):
                 for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                     self.output_view_info(mv_view_wrapper, level=2)
     else:
         if view is not None:
             self.output_view_info(view)
         else:
             self.out("    Not found.")
     self.out('')
示例#3
0
文件: paster.py 项目: gwho/pyramid
 def command(self):
     config_file, section_name, url = self.args
     if not url.startswith('/'):
         url = '/%s' % url
     app = self.get_app(config_file, section_name, loadapp=self.loadapp[0])
     registry = app.registry
     view = self._find_view(url, registry)
     self.out('')
     self.out("URL = %s" % url)
     self.out('')
     if view is not None:
         self.out("    context: %s" % view.__request_attrs__['context'])
         self.out("    view name: %s" % view.__request_attrs__['view_name'])
     if IMultiView.providedBy(view):
         for dummy, view_wrapper, dummy in view.views:
             self.output_view_info(view_wrapper)
             if IMultiView.providedBy(view_wrapper):
                 for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                     self.output_view_info(mv_view_wrapper, level=2)
     else:
         if view is not None:
             self.output_view_info(view)
         else:
             self.out("    Not found.")
     self.out('')
示例#4
0
    def run(self):
        if not self.args.config_uri or not self.args.url:
            self.out('Command requires a config file arg and a url arg')
            return 2
        config_uri = self.args.config_uri
        config_vars = parse_vars(self.args.config_vars)
        url = self.args.url

        self.setup_logging(config_uri, global_conf=config_vars)

        if not url.startswith('/'):
            url = '/%s' % url
        request = Request.blank(url)
        env = self.bootstrap(config_uri, options=config_vars, request=request)
        view = self._find_view(request)
        self.out('')
        self.out("URL = %s" % url)
        self.out('')
        if view is not None:
            self.out("    context: %s" % view.__request_attrs__['context'])
            self.out("    view name: %s" % view.__request_attrs__['view_name'])
        if IMultiView.providedBy(view):
            for dummy, view_wrapper, dummy in view.views:
                self.output_view_info(view_wrapper)
                if IMultiView.providedBy(view_wrapper):
                    for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                        self.output_view_info(mv_view_wrapper, level=2)
        else:
            if view is not None:
                self.output_view_info(view)
            else:
                self.out("    Not found.")
        self.out('')
        env['closer']()
        return 0
示例#5
0
文件: pviews.py 项目: 7924102/pyramid
    def run(self):
        if len(self.args) < 2:
            self.out('Command requires a config file arg and a url arg')
            return 2
        config_uri = self.args[0]
        url = self.args[1]

        if not url.startswith('/'):
            url = '/%s' % url
        request = Request.blank(url)
        env = self.bootstrap[0](config_uri, options=parse_vars(self.args[2:]),
                                request=request)
        view = self._find_view(request)
        self.out('')
        self.out("URL = %s" % url)
        self.out('')
        if view is not None:
            self.out("    context: %s" % view.__request_attrs__['context'])
            self.out("    view name: %s" % view.__request_attrs__['view_name'])
        if IMultiView.providedBy(view):
            for dummy, view_wrapper, dummy in view.views:
                self.output_view_info(view_wrapper)
                if IMultiView.providedBy(view_wrapper):
                    for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                        self.output_view_info(mv_view_wrapper, level=2)
        else:
            if view is not None:
                self.output_view_info(view)
            else:
                self.out("    Not found.")
        self.out('')
        env['closer']()
        return 0
示例#6
0
 def command(self):
     config_file, section_name, url = self.args
     if not url.startswith('/'):
         url = '/%s' % url
     app = self.get_app(config_file, section_name, loadapp=self.loadapp[0])
     registry = app.registry
     view = self._find_view(url, registry)
     self.out('')
     self.out("URL = %s" % url)
     self.out('')
     if view is not None:
         self.out("    context: %s" % view.__request_attrs__['context'])
         self.out("    view name: %s" % view.__request_attrs__['view_name'])
     if IMultiView.providedBy(view):
         for dummy, view_wrapper, dummy in view.views:
             self.output_view_info(view_wrapper)
             if IMultiView.providedBy(view_wrapper):
                 for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                     self.output_view_info(mv_view_wrapper, level=2)
     else:
         if view is not None:
             self.output_view_info(view)
         else:
             self.out("    Not found.")
     self.out('')
示例#7
0
 def run(self):
     if len(self.args) < 2:
         self.out('Command requires a config file arg and a url arg')
         return 2
     config_uri, url = self.args
     if not url.startswith('/'):
         url = '/%s' % url
     env = self.bootstrap[0](config_uri)
     registry = env['registry']
     view = self._find_view(url, registry)
     self.out('')
     self.out("URL = %s" % url)
     self.out('')
     if view is not None:
         self.out("    context: %s" % view.__request_attrs__['context'])
         self.out("    view name: %s" % view.__request_attrs__['view_name'])
     if IMultiView.providedBy(view):
         for dummy, view_wrapper, dummy in view.views:
             self.output_view_info(view_wrapper)
             if IMultiView.providedBy(view_wrapper):
                 for dummy, mv_view_wrapper, dummy in view_wrapper.views:
                     self.output_view_info(mv_view_wrapper, level=2)
     else:
         if view is not None:
             self.output_view_info(view)
         else:
             self.out("    Not found.")
     self.out('')
     return 0
示例#8
0
  def getEndpoints(self, options, context):

    if isstr(options.view) and self.settings.config:
      # TODO: is this the "right" way?...
      # TODO: DRY... see cli.py!
      from pyramid.scripts.pviews import PViewsCommand
      pvcomm = PViewsCommand([])
      options.view = pvcomm._find_view(options.view, self.settings.config.registry)

    # todo: remove requirement on a single view...
    if IMultiView.providedBy(options.view):
      options.view = options.view.views[0][1]

    # TODO: add support for any kind of view_callable...
    if not isinstance(options.view, Controller):
      try:
        # TODO: this is *ridiculous*... it is extracting the controller from
        #       the closure... ugh. *obviously* not the right way...
        options.view = options.view.__closure__[1].cell_contents.__wraps__.__closure__[0].cell_contents
        # TODO: handle case where options.view is a subclass (but not instance) of Controller...
        if not isinstance(options.view, Controller):
          raise TypeError('not a controller: %r', options.view)
      except Exception:
        log.exception('invalid target for pyramid-describe: %r', options.view)
        raise TypeError(_('the URL "{}" does not point to a pyramid_controllers.Controller', options.root))
    # todo: further decorate `context`...
    for entry in self._walkEntries(options, None):
      if entry.methods:
        entry.methods = filter(None, [
          options.eparsers.filter(e, context)
          for e in entry.methods])
        entry.methods = sorted(entry.methods, key=self.methOrderKey)
      entry = options.eparsers.filter(entry, context)
      if entry:
        yield entry
示例#9
0
 def test__find_view_route_multiview_no_view_registered(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IMultiView
     from pyramid.interfaces import IRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     def view1():pass
     def view2():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute1(Interface):
         pass
     class IMyRoute2(Interface):
         pass
     registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
     registry.registerUtility(IMyRoute2, IRouteRequest, name='b')
     @implementer(IMyRoot)
     class Factory(object):
         def __init__(self, request):
             pass
     registry.registerUtility(Factory, IRootFactory)
     routes = [dummy.DummyRoute('a', '/a', matchdict={}),
               dummy.DummyRoute('b', '/a', matchdict={})]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     request = self._makeRequest('/a', registry)
     result = command._find_view(request)
     self.assertTrue(IMultiView.providedBy(result))
示例#10
0
 def test__find_view_route_multiview_no_view_registered(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IMultiView
     from pyramid.interfaces import IRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     def view1():pass
     def view2():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute1(Interface):
         pass
     class IMyRoute2(Interface):
         pass
     registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
     registry.registerUtility(IMyRoute2, IRouteRequest, name='b')
     @implementer(IMyRoot)
     class Factory(object):
         def __init__(self, request):
             pass
     registry.registerUtility(Factory, IRootFactory)
     routes = [dummy.DummyRoute('a', '/a', matchdict={}),
               dummy.DummyRoute('b', '/a', matchdict={})]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertTrue(IMultiView.providedBy(result))
示例#11
0
文件: pviews.py 项目: 7924102/pyramid
 def output_view_info(self, view_wrapper, level=1):
     indent = "    " * level
     name = getattr(view_wrapper, '__name__', '')
     module = getattr(view_wrapper, '__module__', '')
     attr = getattr(view_wrapper, '__view_attr__', None)
     request_attrs = getattr(view_wrapper, '__request_attrs__', {})
     if attr is not None:
         view_callable = "%s.%s.%s" % (module, name, attr)
     else:
         attr = view_wrapper.__class__.__name__
         if attr == 'function':
             attr = name
         view_callable = "%s.%s" % (module, attr)
     self.out('')
     if 'matched_route' in request_attrs:
         self.out("%sRoute:" % indent)
         self.out("%s------" % indent)
         self.output_route_attrs(request_attrs, indent)
         permission = getattr(view_wrapper, '__permission__', None)
         if not IMultiView.providedBy(view_wrapper):
             # single view for this route, so repeat call without route data
             del request_attrs['matched_route']
             self.output_view_info(view_wrapper, level + 1)
     else:
         self.out("%sView:" % indent)
         self.out("%s-----" % indent)
         self.out("%s%s" % (indent, view_callable))
         permission = getattr(view_wrapper, '__permission__', None)
         if permission is not None:
             self.out("%srequired permission = %s" % (indent, permission))
         predicates = getattr(view_wrapper, '__predicates__', None)
         if predicates is not None:
             predicate_text = ', '.join([p.text() for p in predicates])
             self.out("%sview predicates (%s)" % (indent, predicate_text))
示例#12
0
 def output_view_info(self, view_wrapper, level=1):
     indent = "    " * level
     name = getattr(view_wrapper, '__name__', '')
     module = getattr(view_wrapper, '__module__', '')
     attr = getattr(view_wrapper, '__view_attr__', None)
     request_attrs = getattr(view_wrapper, '__request_attrs__', {})
     if attr is not None:
         view_callable = "%s.%s.%s" % (module, name, attr)
     else:
         attr = view_wrapper.__class__.__name__
         if attr == 'function':
             attr = name
         view_callable = "%s.%s" % (module, attr)
     self.out('')
     if 'matched_route' in request_attrs:
         self.out("%sRoute:" % indent)
         self.out("%s------" % indent)
         self.output_route_attrs(request_attrs, indent)
         permission = getattr(view_wrapper, '__permission__', None)
         if not IMultiView.providedBy(view_wrapper):
             # single view for this route, so repeat call without route data
             del request_attrs['matched_route']
             self.output_view_info(view_wrapper, level + 1)
     else:
         self.out("%sView:" % indent)
         self.out("%s-----" % indent)
         self.out("%s%s" % (indent, view_callable))
         permission = getattr(view_wrapper, '__permission__', None)
         if permission is not None:
             self.out("%srequired permission = %s" % (indent, permission))
         predicates = getattr(view_wrapper, '__predicates__', None)
         if predicates is not None:
             predicate_text = ', '.join([p.text() for p in predicates])
             self.out("%sview predicates (%s)" % (indent, predicate_text))
示例#13
0
    def test__find_view_route_multiview(self):
        from zope.interface import Interface, implementer

        from pyramid.interfaces import (
            IMultiView,
            IRootFactory,
            IRouteRequest,
            IView,
            IViewClassifier,
        )
        from pyramid.registry import Registry

        registry = Registry()

        def view1():  # pragma: no cover
            pass

        def view2():  # pragma: no cover
            pass

        class IMyRoot(Interface):
            pass

        class IMyRoute1(Interface):
            pass

        class IMyRoute2(Interface):
            pass

        registry.registerAdapter(
            view1, (IViewClassifier, IMyRoute1, IMyRoot), IView, ''
        )
        registry.registerAdapter(
            view2, (IViewClassifier, IMyRoute2, IMyRoot), IView, ''
        )
        registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
        registry.registerUtility(IMyRoute2, IRouteRequest, name='b')

        @implementer(IMyRoot)
        class Factory:
            def __init__(self, request):
                pass

        registry.registerUtility(Factory, IRootFactory)
        routes = [
            dummy.DummyRoute('a', '/a', matchdict={}),
            dummy.DummyRoute('b', '/a', matchdict={}),
        ]
        self._register_mapper(registry, routes)
        command = self._makeOne(registry=registry)
        request = self._makeRequest('/a', registry)
        result = command._find_view(request)
        self.assertTrue(IMultiView.providedBy(result))
        self.assertEqual(len(result.views), 2)
        self.assertTrue((None, view1, None) in result.views)
        self.assertTrue((None, view2, None) in result.views)
示例#14
0
    def test__find_view_route_multiview(self):
        from zope.interface import Interface
        from zope.interface import implementer
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IView
        from pyramid.interfaces import IMultiView
        from pyramid.interfaces import IRootFactory
        from pyramid.registry import Registry

        registry = Registry()

        def view1():  # pragma: no cover
            pass

        def view2():  # pragma: no cover
            pass

        class IMyRoot(Interface):
            pass

        class IMyRoute1(Interface):
            pass

        class IMyRoute2(Interface):
            pass

        registry.registerAdapter(
            view1, (IViewClassifier, IMyRoute1, IMyRoot), IView, ''
        )
        registry.registerAdapter(
            view2, (IViewClassifier, IMyRoute2, IMyRoot), IView, ''
        )
        registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
        registry.registerUtility(IMyRoute2, IRouteRequest, name='b')

        @implementer(IMyRoot)
        class Factory(object):
            def __init__(self, request):
                pass

        registry.registerUtility(Factory, IRootFactory)
        routes = [
            dummy.DummyRoute('a', '/a', matchdict={}),
            dummy.DummyRoute('b', '/a', matchdict={}),
        ]
        self._register_mapper(registry, routes)
        command = self._makeOne(registry=registry)
        request = self._makeRequest('/a', registry)
        result = command._find_view(request)
        self.assertTrue(IMultiView.providedBy(result))
        self.assertEqual(len(result.views), 2)
        self.assertTrue((None, view1, None) in result.views)
        self.assertTrue((None, view2, None) in result.views)
示例#15
0
    def test__find_view_route_multiview(self):
        from zope.interface import Interface
        from zope.interface import implements
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IView
        from pyramid.interfaces import IMultiView
        from pyramid.interfaces import IRootFactory
        from pyramid.registry import Registry
        registry = Registry()

        def view1():
            pass

        def view2():
            pass

        class IMyRoot(Interface):
            pass

        class IMyRoute1(Interface):
            pass

        class IMyRoute2(Interface):
            pass

        registry.registerAdapter(view1, (IViewClassifier, IMyRoute1, IMyRoot),
                                 IView, '')
        registry.registerAdapter(view2, (IViewClassifier, IMyRoute2, IMyRoot),
                                 IView, '')
        registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
        registry.registerUtility(IMyRoute2, IRouteRequest, name='b')

        class Factory(object):
            implements(IMyRoot)

            def __init__(self, request):
                pass

        registry.registerUtility(Factory, IRootFactory)
        routes = [
            DummyRoute('a', '/a', matchdict={}),
            DummyRoute('b', '/a', matchdict={})
        ]
        self._register_mapper(registry, routes)
        command = self._makeOne()
        result = command._find_view('/a', registry)
        self.failUnless(IMultiView.providedBy(result))
        self.assertEqual(len(result.views), 2)
        self.failUnless((None, view1, None) in result.views)
        self.failUnless((None, view2, None) in result.views)
示例#16
0
    def getEndpoints(self, options, context):

        if isstr(options.view) and self.settings.config:
            # TODO: is this the "right" way?...
            # TODO: DRY... see cli.py!
            from pyramid.scripts.pviews import PViewsCommand
            pvcomm = PViewsCommand([])
            options.view = pvcomm._find_view(options.view,
                                             self.settings.config.registry)

        # todo: remove requirement on a single view...
        if IMultiView.providedBy(options.view):
            options.view = options.view.views[0][1]

        # TODO: add support for any kind of view_callable...
        if not isinstance(options.view, Controller):
            try:
                # TODO: this is *ridiculous*... it is extracting the controller from
                #       the closure... ugh. *obviously* not the right way...
                options.view = options.view.__closure__[
                    1].cell_contents.__wraps__.__closure__[0].cell_contents
                # TODO: handle case where options.view is a subclass (but not instance) of Controller...
                if not isinstance(options.view, Controller):
                    raise TypeError('not a controller: %r', options.view)
            except Exception:
                log.exception('invalid target for pyramid-describe: %r',
                              options.view)
                raise TypeError(
                    _(
                        'the URL "{}" does not point to a pyramid_controllers.Controller',
                        options.root))
        # todo: further decorate `context`...
        for entry in self._walkEntries(options, None):
            if entry.methods:
                entry.methods = filter(None, [
                    options.eparsers.filter(e, context) for e in entry.methods
                ])
                entry.methods = sorted(entry.methods, key=self.methOrderKey)
            entry = options.eparsers.filter(entry, context)
            if entry:
                yield entry
示例#17
0
文件: pviews.py 项目: 7924102/pyramid
    def _find_view(self, request):
        """
        Accept ``url`` and ``registry``; create a :term:`request` and
        find a :app:`Pyramid` view based on introspection of :term:`view
        configuration` within the application registry; return the view.
        """
        from zope.interface import providedBy
        from zope.interface import implementer
        from pyramid.interfaces import IRequest
        from pyramid.interfaces import IRootFactory
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IRoutesMapper
        from pyramid.interfaces import ITraverser
        from pyramid.traversal import DefaultRootFactory
        from pyramid.traversal import ResourceTreeTraverser

        registry = request.registry
        q = registry.queryUtility
        root_factory = q(IRootFactory, default=DefaultRootFactory)
        routes_mapper = q(IRoutesMapper)

        adapters = registry.adapters

        @implementer(IMultiView)
        class RoutesMultiView(object):

            def __init__(self, infos, context_iface, root_factory, request):
                self.views = []
                for info in infos:
                    match, route = info['match'], info['route']
                    if route is not None:
                        request_iface = registry.queryUtility(
                            IRouteRequest,
                            name=route.name,
                            default=IRequest)
                        views = _find_views(
                            request.registry,
                            request_iface,
                            context_iface,
                            ''
                            )
                        if not views:
                            continue
                        view = views[0]
                        view.__request_attrs__ = {}
                        view.__request_attrs__['matchdict'] = match
                        view.__request_attrs__['matched_route'] = route
                        root_factory = route.factory or root_factory
                        root = root_factory(request)
                        traverser = adapters.queryAdapter(root, ITraverser)
                        if traverser is None:
                            traverser = ResourceTreeTraverser(root)
                        tdict = traverser(request)
                        view.__request_attrs__.update(tdict)
                        if not hasattr(view, '__view_attr__'):
                            view.__view_attr__ = ''
                        self.views.append((None, view, None))

        context = None
        routes_multiview = None
        attrs = request.__dict__
        request_iface = IRequest

        # find the root object
        if routes_mapper is not None:
            infos = self._find_multi_routes(routes_mapper, request)
            if len(infos) == 1:
                info = infos[0]
                match, route = info['match'], info['route']
                if route is not None:
                    attrs['matchdict'] = match
                    attrs['matched_route'] = route
                    request.environ['bfg.routes.matchdict'] = match
                    request_iface = registry.queryUtility(
                        IRouteRequest,
                        name=route.name,
                        default=IRequest)
                    root_factory = route.factory or root_factory
            if len(infos) > 1:
                routes_multiview = infos

        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 = (tdict['context'], tdict['view_name'])

        attrs.update(tdict)

        # find a view callable
        context_iface = providedBy(context)
        if routes_multiview is None:
            views = _find_views(
                request.registry,
                request_iface,
                context_iface,
                view_name,
                )
            if views:
                view = views[0]
            else:
                view = None
        else:
            view = RoutesMultiView(infos, context_iface, root_factory, request)

        # routes are not registered with a view name
        if view is None:
            views = _find_views(
                request.registry,
                request_iface,
                context_iface,
                '',
                )
            if views:
                view = views[0]
            else:
                view = None
            # we don't want a multiview here
            if IMultiView.providedBy(view):
                view = None

        if view is not None:
            view.__request_attrs__ = attrs

        return view
示例#18
0
    def _find_view(self, request):
        """
        Accept ``url`` and ``registry``; create a :term:`request` and
        find a :app:`Pyramid` view based on introspection of :term:`view
        configuration` within the application registry; return the view.
        """
        from zope.interface import providedBy
        from zope.interface import implementer
        from pyramid.interfaces import IRequest
        from pyramid.interfaces import IRootFactory
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IRoutesMapper
        from pyramid.interfaces import ITraverser
        from pyramid.traversal import DefaultRootFactory
        from pyramid.traversal import ResourceTreeTraverser

        registry = request.registry
        q = registry.queryUtility
        root_factory = q(IRootFactory, default=DefaultRootFactory)
        routes_mapper = q(IRoutesMapper)

        adapters = registry.adapters

        @implementer(IMultiView)
        class RoutesMultiView(object):
            def __init__(self, infos, context_iface, root_factory, request):
                self.views = []
                for info in infos:
                    match, route = info['match'], info['route']
                    if route is not None:
                        request_iface = registry.queryUtility(
                            IRouteRequest, name=route.name, default=IRequest
                        )
                        views = _find_views(
                            request.registry, request_iface, context_iface, ''
                        )
                        if not views:
                            continue
                        view = views[0]
                        view.__request_attrs__ = {}
                        view.__request_attrs__['matchdict'] = match
                        view.__request_attrs__['matched_route'] = route
                        root_factory = route.factory or root_factory
                        root = root_factory(request)
                        traverser = adapters.queryAdapter(root, ITraverser)
                        if traverser is None:
                            traverser = ResourceTreeTraverser(root)
                        tdict = traverser(request)
                        view.__request_attrs__.update(tdict)
                        if not hasattr(view, '__view_attr__'):
                            view.__view_attr__ = ''
                        self.views.append((None, view, None))

        context = None
        routes_multiview = None
        attrs = request.__dict__
        request_iface = IRequest

        # find the root object
        if routes_mapper is not None:
            infos = self._find_multi_routes(routes_mapper, request)
            if len(infos) == 1:
                info = infos[0]
                match, route = info['match'], info['route']
                if route is not None:
                    attrs['matchdict'] = match
                    attrs['matched_route'] = route
                    request.environ['bfg.routes.matchdict'] = match
                    request_iface = registry.queryUtility(
                        IRouteRequest, name=route.name, default=IRequest
                    )
                    root_factory = route.factory or root_factory
            if len(infos) > 1:
                routes_multiview = infos

        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 = (tdict['context'], tdict['view_name'])

        attrs.update(tdict)

        # find a view callable
        context_iface = providedBy(context)
        if routes_multiview is None:
            views = _find_views(
                request.registry, request_iface, context_iface, view_name
            )
            if views:
                view = views[0]
            else:
                view = None
        else:
            view = RoutesMultiView(infos, context_iface, root_factory, request)

        # routes are not registered with a view name
        if view is None:
            views = _find_views(
                request.registry, request_iface, context_iface, ''
            )
            if views:
                view = views[0]
            else:
                view = None
            # we don't want a multiview here
            if IMultiView.providedBy(view):
                view = None

        if view is not None:
            view.__request_attrs__ = attrs

        return view
示例#19
0
    def register(permission=permission, renderer=renderer):
        # the discrim_func above is guaranteed to have been called already
        order = view_intr['order']
        preds = view_intr['predicates']
        phash = view_intr['phash']
        request_iface = IRequest
        if route_name is not None:
            request_iface = self.registry.queryUtility(IRouteRequest,
                                                       name=route_name)
            if request_iface is None:
                # route configuration should have already happened in
                # phase 2
                raise ConfigurationError(
                    'No route named %s found for view registration' %
                    route_name)

        if renderer is None:
            # use default renderer if one exists (reg'd in phase 1)
            if self.registry.queryUtility(IRendererFactory) is not None:
                renderer = renderers.RendererHelper(name=None,
                                                    package=self.package,
                                                    registry=self.registry)

        if permission is None:
            # intent: will be None if no default permission is registered
            # (reg'd in phase 1)
            permission = self.registry.queryUtility(IDefaultPermission)

        # added by discrim_func above during conflict resolving
        preds = view_intr['predicates']
        order = view_intr['order']
        phash = view_intr['phash']

        # __no_permission_required__ handled by _secure_view
        deriver = ViewDeriver(
            registry=self.registry,
            permission=permission,
            predicates=preds,
            attr=attr,
            renderer=renderer,
            wrapper_viewname=wrapper,
            viewname=name,
            accept=accept,
            order=order,
            phash=phash,
            package=self.package,
            mapper=mapper,
            decorator=decorator,
            http_cache=http_cache,
        )
        derived_view = deriver(view)
        derived_view.__discriminator__ = lambda *arg: discriminator
        # __discriminator__ is used by superdynamic systems
        # that require it for introspection after manual view lookup;
        # see also MultiView.__discriminator__
        view_intr['derived_callable'] = derived_view

        registered = self.registry.adapters.registered

        # A multiviews is a set of views which are registered for
        # exactly the same context type/request type/name triad.  Each
        # consituent view in a multiview differs only by the
        # predicates which it possesses.

        # To find a previously registered view for a context
        # type/request type/name triad, we need to use the
        # ``registered`` method of the adapter registry rather than
        # ``lookup``.  ``registered`` ignores interface inheritance
        # for the required and provided arguments, returning only a
        # view registered previously with the *exact* triad we pass
        # in.

        # We need to do this three times, because we use three
        # different interfaces as the ``provided`` interface while
        # doing registrations, and ``registered`` performs exact
        # matches on all the arguments it receives.

        old_view = None

        for view_type in (IView, ISecuredView, IMultiView):
            old_view = registered((IViewClassifier, request_iface, r_context),
                                  view_type, name)
            if old_view is not None:
                break

        isexc = isexception(context)

        def regclosure():
            if hasattr(derived_view, '__call_permissive__'):
                view_iface = ISecuredView
            else:
                view_iface = IView
            self.registry.registerAdapter(
                derived_view, (IViewClassifier, request_iface, context),
                view_iface, name)
            if isexc:
                self.registry.registerAdapter(
                    derived_view,
                    (IExceptionViewClassifier, request_iface, context),
                    view_iface, name)

        is_multiview = IMultiView.providedBy(old_view)
        old_phash = getattr(old_view, '__phash__', DEFAULT_PHASH)

        if old_view is None:
            # - No component was yet registered for any of our I*View
            #   interfaces exactly; this is the first view for this
            #   triad.
            regclosure()

        elif (not is_multiview) and (old_phash == phash):
            # - A single view component was previously registered with
            #   the same predicate hash as this view; this registration
            #   is therefore an override.
            regclosure()

        else:
            # - A view or multiview was already registered for this
            #   triad, and the new view is not an override.

            # XXX we could try to be more efficient here and register
            # a non-secured view for a multiview if none of the
            # multiview's consituent views have a permission
            # associated with them, but this code is getting pretty
            # rough already
            if is_multiview:
                multiview = old_view
            else:
                multiview = MultiView(name)
                old_accept = getattr(old_view, '__accept__', None)
                old_order = getattr(old_view, '__order__', MAX_ORDER)
                multiview.add(old_view, old_order, old_accept, old_phash)
            multiview.add(derived_view, order, accept, phash)
            for view_type in (IView, ISecuredView):
                # unregister any existing views
                self.registry.adapters.unregister(
                    (IViewClassifier, request_iface, r_context),
                    view_type,
                    name=name)
                if isexc:
                    self.registry.adapters.unregister(
                        (IExceptionViewClassifier, request_iface, r_context),
                        view_type,
                        name=name)
            self.registry.registerAdapter(
                multiview, (IViewClassifier, request_iface, context),
                IMultiView,
                name=name)
            if isexc:
                self.registry.registerAdapter(
                    multiview,
                    (IExceptionViewClassifier, request_iface, context),
                    IMultiView,
                    name=name)
        renderer_type = getattr(renderer, 'type', None)  # gard against None
        intrspc = self.introspector
        if (renderer_type is not None and tmpl_intr is not None
                and intrspc is not None and intrspc.get(
                    'renderer factories', renderer_type) is not None):
            # allow failure of registered template factories to be deferred
            # until view execution, like other bad renderer factories; if
            # we tried to relate this to an existing renderer factory
            # without checking if it the factory actually existed, we'd end
            # up with a KeyError at startup time, which is inconsistent
            # with how other bad renderer registrations behave (they throw
            # a ValueError at view execution time)
            tmpl_intr.relate('renderer factories', renderer.type)
示例#20
0
文件: paster.py 项目: gwho/pyramid
    def _find_view(self, url, registry):
        """
        Accept ``url`` and ``registry``; create a :term:`request` and
        find a :app:`Pyramid` view based on introspection of :term:`view
        configuration` within the application registry; return the view.
        """
        from zope.interface import providedBy
        from zope.interface import implements
        from pyramid.interfaces import IRequest
        from pyramid.interfaces import IRootFactory
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IRequestFactory
        from pyramid.interfaces import IRoutesMapper
        from pyramid.interfaces import IView
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import ITraverser
        from pyramid.request import Request
        from pyramid.traversal import DefaultRootFactory
        from pyramid.traversal import ResourceTreeTraverser
            
        q = registry.queryUtility
        root_factory = q(IRootFactory, default=DefaultRootFactory)
        routes_mapper = q(IRoutesMapper)
        request_factory = q(IRequestFactory, default=Request)

        adapters = registry.adapters
        request = None

        class RoutesMultiView(object):
            implements(IMultiView)

            def __init__(self, infos, context_iface, root_factory, request):
                self.views = []
                for info in infos:
                    match, route = info['match'], info['route']
                    if route is not None:
                        request_iface = registry.queryUtility(
                            IRouteRequest,
                            name=route.name,
                            default=IRequest)
                        view = adapters.lookup(
                            (IViewClassifier, request_iface, context_iface),
                            IView, name='', default=None)
                        if view is None:
                            continue
                        view.__request_attrs__ = {}
                        view.__request_attrs__['matchdict'] = match
                        view.__request_attrs__['matched_route'] = route
                        root_factory = route.factory or root_factory
                        root = root_factory(request)
                        traverser = adapters.queryAdapter(root, ITraverser)
                        if traverser is None:
                            traverser = ResourceTreeTraverser(root)
                        tdict = traverser(request)
                        view.__request_attrs__.update(tdict)
                        if not hasattr(view, '__view_attr__'):
                            view.__view_attr__ = ''
                        self.views.append((None, view, None))


        # create the request
        environ = {
            'wsgi.url_scheme':'http',
            'SERVER_NAME':'localhost',
            'SERVER_PORT':'8080',
            'REQUEST_METHOD':'GET',
            'PATH_INFO':url,
            }
        request = request_factory(environ)
        context = None
        routes_multiview = None
        attrs = request.__dict__
        attrs['registry'] = registry
        request_iface = IRequest

        # find the root object
        if routes_mapper is not None:
            infos = self._find_multi_routes(routes_mapper, request)
            if len(infos) == 1:
                info = infos[0]
                match, route = info['match'], info['route']
                if route is not None:
                    attrs['matchdict'] = match
                    attrs['matched_route'] = route
                    request.environ['bfg.routes.matchdict'] = match
                    request_iface = registry.queryUtility(
                        IRouteRequest,
                        name=route.name,
                        default=IRequest)
                    root_factory = route.factory or root_factory
            if len(infos) > 1:
                routes_multiview = infos

        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)

        # find a view callable
        context_iface = providedBy(context)
        if routes_multiview is None:
            view = adapters.lookup(
                (IViewClassifier, request_iface, context_iface),
                IView, name=view_name, default=None)
        else:
            view = RoutesMultiView(infos, context_iface, root_factory, request)

        # routes are not registered with a view name
        if view is None:
            view = adapters.lookup(
                (IViewClassifier, request_iface, context_iface),
                IView, name='', default=None)
            # we don't want a multiview here
            if IMultiView.providedBy(view):
                view = None

        if view is not None:
            view.__request_attrs__ = attrs

        return view
示例#21
0
    def run(self, quiet=False):
        if not self.args:
            self.out('requires a config file argument')
            return 2

        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IView
        from pyramid.interfaces import IMultiView

        from zope.interface import Interface
        config_uri = self.args[0]

        env = self.bootstrap[0](config_uri, options=parse_vars(self.args[1:]))
        registry = env['registry']
        mapper = self._get_mapper(registry)
        if mapper is not None:
            mapped_routes = [('Name', 'Pattern', 'View')]

            max_name = len('Name')
            max_pattern = len('Pattern')
            max_view = len('View')

            routes = mapper.get_routes()

            if not routes:
                return 0

            mapped_routes.append((
                '-' * max_name,
                '-' * max_pattern,
                '-' * max_view,
            ))

            for route in routes:
                pattern = route.pattern
                if not pattern.startswith('/'):
                    pattern = '/' + pattern
                request_iface = registry.queryUtility(IRouteRequest,
                                                      name=route.name)
                view_callable = None

                if (request_iface is None) or (route.factory is not None):
                    view_callable = '<unknown>'
                else:
                    view_callable = registry.adapters.lookup(
                        (IViewClassifier, request_iface, Interface),
                        IView, name='', default=None)

                    if view_callable is not None:
                        if IMultiView.providedBy(view_callable):
                            view_callables = [
                                x[1] for x in view_callable.views
                            ]
                        else:
                            view_callables = [view_callable]

                        for view_func in view_callables:
                            view_callable = '%s.%s' % (
                                view_func.__module__,
                                view_func.__name__,
                            )
                    else:
                        view_callable = str(None)

                if len(route.name) > max_name:
                    max_name = len(route.name)

                if len(pattern) > max_pattern:
                    max_pattern = len(pattern)

                if len(view_callable) > max_view:
                    max_view = len(view_callable)

                mapped_routes.append((route.name, pattern, view_callable))

            fmt = '%-{0}s %-{1}s %-{2}s'.format(
                max_name + PAD,
                max_pattern + PAD,
                max_view + PAD,
            )

            for route_data in mapped_routes:
                self.out(fmt % route_data)

        return 0
示例#22
0
    def _find_view(self, url, registry):
        """
        Accept ``url`` and ``registry``; create a :term:`request` and
        find a :app:`Pyramid` view based on introspection of :term:`view
        configuration` within the application registry; return the view.
        """
        from zope.interface import providedBy
        from zope.interface import implementer
        from pyramid.interfaces import IRequest
        from pyramid.interfaces import IRootFactory
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IRequestFactory
        from pyramid.interfaces import IRoutesMapper
        from pyramid.interfaces import IView
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import ITraverser
        from pyramid.request import Request
        from pyramid.traversal import DefaultRootFactory
        from pyramid.traversal import ResourceTreeTraverser

        q = registry.queryUtility
        root_factory = q(IRootFactory, default=DefaultRootFactory)
        routes_mapper = q(IRoutesMapper)
        request_factory = q(IRequestFactory, default=Request)

        adapters = registry.adapters
        request = None

        @implementer(IMultiView)
        class RoutesMultiView(object):
            def __init__(self, infos, context_iface, root_factory, request):
                self.views = []
                for info in infos:
                    match, route = info['match'], info['route']
                    if route is not None:
                        request_iface = registry.queryUtility(IRouteRequest,
                                                              name=route.name,
                                                              default=IRequest)
                        view = adapters.lookup(
                            (IViewClassifier, request_iface, context_iface),
                            IView,
                            name='',
                            default=None)
                        if view is None:
                            continue
                        view.__request_attrs__ = {}
                        view.__request_attrs__['matchdict'] = match
                        view.__request_attrs__['matched_route'] = route
                        root_factory = route.factory or root_factory
                        root = root_factory(request)
                        traverser = adapters.queryAdapter(root, ITraverser)
                        if traverser is None:
                            traverser = ResourceTreeTraverser(root)
                        tdict = traverser(request)
                        view.__request_attrs__.update(tdict)
                        if not hasattr(view, '__view_attr__'):
                            view.__view_attr__ = ''
                        self.views.append((None, view, None))

        # create the request
        environ = {
            'wsgi.url_scheme': 'http',
            'SERVER_NAME': 'localhost',
            'SERVER_PORT': '8080',
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': url,
        }
        request = request_factory(environ)
        context = None
        routes_multiview = None
        attrs = request.__dict__
        attrs['registry'] = registry
        request_iface = IRequest

        # find the root object
        if routes_mapper is not None:
            infos = self._find_multi_routes(routes_mapper, request)
            if len(infos) == 1:
                info = infos[0]
                match, route = info['match'], info['route']
                if route is not None:
                    attrs['matchdict'] = match
                    attrs['matched_route'] = route
                    request.environ['bfg.routes.matchdict'] = match
                    request_iface = registry.queryUtility(IRouteRequest,
                                                          name=route.name,
                                                          default=IRequest)
                    root_factory = route.factory or root_factory
            if len(infos) > 1:
                routes_multiview = infos

        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)

        # find a view callable
        context_iface = providedBy(context)
        if routes_multiview is None:
            view = adapters.lookup(
                (IViewClassifier, request_iface, context_iface),
                IView,
                name=view_name,
                default=None)
        else:
            view = RoutesMultiView(infos, context_iface, root_factory, request)

        # routes are not registered with a view name
        if view is None:
            view = adapters.lookup(
                (IViewClassifier, request_iface, context_iface),
                IView,
                name='',
                default=None)
            # we don't want a multiview here
            if IMultiView.providedBy(view):
                view = None

        if view is not None:
            view.__request_attrs__ = attrs

        return view
示例#23
0
    def register(permission=permission, renderer=renderer):
        # the discrim_func above is guaranteed to have been called already
        order = view_intr['order']
        preds = view_intr['predicates']
        phash = view_intr['phash']
        request_iface = IRequest
        if route_name is not None:
            request_iface = self.registry.queryUtility(IRouteRequest,
                                                       name=route_name)
            if request_iface is None:
                # route configuration should have already happened in
                # phase 2
                raise ConfigurationError(
                    'No route named %s found for view registration' %
                    route_name)

        if renderer is None:
            # use default renderer if one exists (reg'd in phase 1)
            if self.registry.queryUtility(IRendererFactory) is not None:
                renderer = renderers.RendererHelper(
                    name=None,
                    package=self.package,
                    registry=self.registry
                    )

        if permission is None:
            # intent: will be None if no default permission is registered
            # (reg'd in phase 1)
            permission = self.registry.queryUtility(IDefaultPermission)

        # added by discrim_func above during conflict resolving
        preds = view_intr['predicates']
        order = view_intr['order']
        phash = view_intr['phash']

        # __no_permission_required__ handled by _secure_view
        deriver = ViewDeriver(
            registry=self.registry,
            permission=permission,
            predicates=preds,
            attr=attr,
            renderer=renderer,
            wrapper_viewname=wrapper,
            viewname=name,
            accept=accept,
            order=order,
            phash=phash,
            package=self.package,
            mapper=mapper,
            decorator=decorator,
            http_cache=http_cache,
            )
        derived_view = deriver(view)
        derived_view.__discriminator__ = lambda *arg: discriminator
        # __discriminator__ is used by superdynamic systems
        # that require it for introspection after manual view lookup;
        # see also MultiView.__discriminator__
        view_intr['derived_callable'] = derived_view

        registered = self.registry.adapters.registered

        # A multiviews is a set of views which are registered for
        # exactly the same context type/request type/name triad.  Each
        # consituent view in a multiview differs only by the
        # predicates which it possesses.

        # To find a previously registered view for a context
        # type/request type/name triad, we need to use the
        # ``registered`` method of the adapter registry rather than
        # ``lookup``.  ``registered`` ignores interface inheritance
        # for the required and provided arguments, returning only a
        # view registered previously with the *exact* triad we pass
        # in.

        # We need to do this three times, because we use three
        # different interfaces as the ``provided`` interface while
        # doing registrations, and ``registered`` performs exact
        # matches on all the arguments it receives.

        old_view = None

        for view_type in (IView, ISecuredView, IMultiView):
            old_view = registered((IViewClassifier, request_iface,
                                   r_context), view_type, name)
            if old_view is not None:
                break

        isexc = isexception(context)

        def regclosure():
            if hasattr(derived_view, '__call_permissive__'):
                view_iface = ISecuredView
            else:
                view_iface = IView
            self.registry.registerAdapter(
                derived_view,
                (IViewClassifier, request_iface, context), view_iface, name
                )
            if isexc:
                self.registry.registerAdapter(
                    derived_view,
                    (IExceptionViewClassifier, request_iface, context),
                    view_iface, name)

        is_multiview = IMultiView.providedBy(old_view)
        old_phash = getattr(old_view, '__phash__', DEFAULT_PHASH)

        if old_view is None:
            # - No component was yet registered for any of our I*View
            #   interfaces exactly; this is the first view for this
            #   triad.
            regclosure()

        elif (not is_multiview) and (old_phash == phash):
            # - A single view component was previously registered with
            #   the same predicate hash as this view; this registration
            #   is therefore an override.
            regclosure()

        else:
            # - A view or multiview was already registered for this
            #   triad, and the new view is not an override.

            # XXX we could try to be more efficient here and register
            # a non-secured view for a multiview if none of the
            # multiview's consituent views have a permission
            # associated with them, but this code is getting pretty
            # rough already
            if is_multiview:
                multiview = old_view
            else:
                multiview = MultiView(name)
                old_accept = getattr(old_view, '__accept__', None)
                old_order = getattr(old_view, '__order__', MAX_ORDER)
                multiview.add(old_view, old_order, old_accept, old_phash)
            multiview.add(derived_view, order, accept, phash)
            for view_type in (IView, ISecuredView):
                # unregister any existing views
                self.registry.adapters.unregister(
                    (IViewClassifier, request_iface, r_context),
                    view_type, name=name)
                if isexc:
                    self.registry.adapters.unregister(
                        (IExceptionViewClassifier, request_iface,
                         r_context), view_type, name=name)
            self.registry.registerAdapter(
                multiview,
                (IViewClassifier, request_iface, context),
                IMultiView, name=name)
            if isexc:
                self.registry.registerAdapter(
                    multiview,
                    (IExceptionViewClassifier, request_iface, context),
                    IMultiView, name=name)
        renderer_type = getattr(renderer, 'type', None) # gard against None
        intrspc = self.introspector
        if (
            renderer_type is not None and
            tmpl_intr is not None and
            intrspc is not None and
            intrspc.get('renderer factories', renderer_type) is not None
            ):
            # allow failure of registered template factories to be deferred
            # until view execution, like other bad renderer factories; if
            # we tried to relate this to an existing renderer factory
            # without checking if it the factory actually existed, we'd end
            # up with a KeyError at startup time, which is inconsistent
            # with how other bad renderer registrations behave (they throw
            # a ValueError at view execution time)
            tmpl_intr.relate('renderer factories', renderer.type)