本文整理汇总了Python中pyramid.interfaces.IMultiView类的典型用法代码示例。如果您正苦于以下问题:Python IMultiView类的具体用法?Python IMultiView怎么用?Python IMultiView使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IMultiView类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
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
示例2: command
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('')
示例3: command
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('')
示例4: run
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
示例5: test__find_view_route_multiview_no_view_registered
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))
示例6: output_view_info
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))
示例7: getEndpoints
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
示例8: test__find_view_route_multiview
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)
示例9: _find_view
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,
#.........这里部分代码省略.........
示例10: _find_view
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)
#.........这里部分代码省略.........
示例11: register
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(
#.........这里部分代码省略.........
示例12: run
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