def handler(name, dependencies, *provideAdapterArgs): if dependencies: for dep in dependencies: if dep not in library_info: raise ConfigurationError('Resource library "%s" has unsatisfied dependency on "%s".' % (name, dep)) zapi.getGlobalSiteManager().provideAdapter(*provideAdapterArgs)
def handler(name, dependencies, *provideAdapterArgs): if dependencies: for dep in dependencies: if dep not in library_info: raise ConfigurationError( 'Resource library "%s" has unsatisfied dependency on "%s".' % (name, dep)) zapi.getGlobalSiteManager().provideAdapter(*provideAdapterArgs)
def test_getSiteManagerHook(self): from Products.Five.site.localsite import FiveSiteManager from Products.Five.site.utility import SimpleLocalUtilityRegistry local_sm = zapi.getSiteManager(None) self.failIf(local_sm is zapi.getGlobalSiteManager()) self.failUnless(isinstance(local_sm, FiveSiteManager)) local_sm = zapi.getSiteManager(self.folder.site) self.failIf(local_sm is zapi.getGlobalSiteManager()) self.failUnless(isinstance(local_sm, FiveSiteManager)) sm = zapi.getSiteManager() self.failUnless(isinstance(sm.utilities, SimpleLocalUtilityRegistry))
def AddViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, content_factory, arguments, keyword_arguments, set_before_add, set_after_add): class_ = SimpleViewClass( template, used_for=schema, bases=bases, name=name) class_.schema = schema class_.label = label class_.fieldNames = fields class_._factory_or_id = content_factory class_._factory = property(_getFactory, _setFactory) class_._arguments = arguments class_._keyword_arguments = keyword_arguments class_._set_before_add = set_before_add class_._set_after_add = set_after_add class_.generated_form = ViewPageTemplateFile(default_template) defineChecker(class_, NamesChecker( ("__call__", "__getitem__", "browserDefault", "publishTraverse"), permission, ) ) if layer is None: layer = IDefaultBrowserLayer s = zapi.getGlobalSiteManager() s.provideAdapter((for_, layer), Interface, name, class_)
def config_filter_factory(global_conf, **local_conf): appid = local_conf.get('appid') if not appid: # bomb if `appid` is missing. raise ValueError('Variable `appid` is required for paste.ini') connection_string = local_conf.get('connection_string') connection_factory = local_conf.get('connection_factory') if connection_string is not None and connection_factory is not None: # bomb if there's a existing `db_connection` setting. db_connection = local_conf.get('db_connection') if db_connection: raise ValueError('Variable `db_connection` is dead. Please ' 'use `connection_string` and `connection_factory` ' 'instead.') # resolve dotted name. connection_factory = resolve(connection_factory) # create a connection connection = connection_factory(connection_string) # register a global connection using `appid` as the name. gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IZopeDatabaseAdapter, connection, appid) # fixup the `db_connection` argument. local_conf['db_connection'] = appid def filter(app): return Config(app, local_conf) return filter
def provideConnection(name, connection): """ Registers a database connection Uses the global site manager for registering the connection """ gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IZopeDatabaseAdapter, connection, name)
def test_local_utilities(self): gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IInterface, Foo("global")) gsm.provideUtility(IInterface, Foo("global bob"), name="bob") sm = zapi.getSiteManager(self.rootFolder) default = traverse(self.rootFolder, "++etc++site/default") default['foo'] = Foo("local") foo = default['foo'] cm = default.registrationManager for name in ('', 'bob'): registration = UtilityRegistration(name, IInterface, foo) cname = cm.addRegistration(registration) registration = traverse(cm, cname) gout = name and "foo global "+name or "foo global" self.assertEqual(sm.queryUtility(IInterface, name).foo(), gout) registration.status = ActiveStatus self.assertEqual( sm.queryUtility(IInterface, name).foo(), "foo local") registration.status = InactiveStatus self.assertEqual(sm.queryUtility(IInterface, name).foo(), gout)
def EditViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, fulledit_path=None, fulledit_label=None, menu=u''): class_ = makeClassForTemplate(template, globals(), used_for=schema, bases=bases) class_.schema = schema class_.label = label class_.fieldNames = fields class_.fulledit_path = fulledit_path if fulledit_path and (fulledit_label is None): fulledit_label = "Full edit" class_.fulledit_label = fulledit_label class_.generated_form = ZopeTwoPageTemplateFile(default_template) if layer is None: layer = IDefaultBrowserLayer s = zapi.getGlobalSiteManager() s.provideAdapter((for_, layer), Interface, name, class_) # Reminder: the permission we got has already been processed by # BaseFormDirective, that means that zope.Public has been # translated to the CheckerPublic object protectClass(class_, permission) initializeClass(class_)
def testAbortTransactionWithErrorReportingUtility(self): # provide our fake error reporting utility sm = zapi.getGlobalSiteManager() sm.provideUtility(IErrorReportingUtility, ErrorReportingUtility()) class FooError(Exception): pass last_txn_info = self.db.undoInfo()[0] try: raise FooError except FooError: pass self.publication.handleException( self.object, self.request, sys.exc_info(), retry_allowed=False) # assert that the last transaction is NOT our transaction new_txn_info = self.db.undoInfo()[0] self.assertEqual(last_txn_info, new_txn_info) # instead, we expect a message in our logging utility error_log = zapi.getUtility(IErrorReportingUtility) self.assertEqual(len(error_log.exceptions), 1) error_info, request = error_log.exceptions[0] self.assertEqual(error_info[0], FooError) self.assert_(isinstance(error_info[1], FooError)) self.assert_(request is self.request)
def EditViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, fulledit_path=None, fulledit_label=None): class_ = SimpleViewClass(template, used_for=schema, bases=bases, name=name) class_.schema = schema class_.label = label class_.fieldNames = fields class_.fulledit_path = fulledit_path if fulledit_path and (fulledit_label is None): fulledit_label = "Full edit" class_.fulledit_label = fulledit_label class_.generated_form = ViewPageTemplateFile(default_template) defineChecker(class_, NamesChecker(("__call__", "__getitem__", "browserDefault", "publishTraverse"), permission)) if layer is None: layer = IDefaultBrowserLayer s = zapi.getGlobalSiteManager() s.provideAdapter((for_, layer), Interface, name, class_)
def AddViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, content_factory, arguments, keyword_arguments, set_before_add, set_after_add, menu=u''): class_ = makeClassForTemplate(template, globals(), used_for=schema, bases=bases) class_.schema = schema class_.label = label class_.fieldNames = fields class_._factory = content_factory class_._arguments = arguments class_._keyword_arguments = keyword_arguments class_._set_before_add = set_before_add class_._set_after_add = set_after_add class_.generated_form = ZopeTwoPageTemplateFile(default_template) if layer is None: layer = IDefaultBrowserLayer s = zapi.getGlobalSiteManager() s.provideAdapter((for_, layer), Interface, name, class_) # Reminder: the permission we got has already been processed by # BaseFormDirective, that means that zope.Public has been # translated to the CheckerPublic object protectClass(class_, permission) initializeClass(class_)
def test_getLocalInterface_raisesComponentLookupError(self): gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IInterface, Foo("global")) gsm.provideUtility(IBaz, Baz("global baz")) gsm.provideUtility(IInterface, Foo("global bob"), name="bob") self.assertRaises(ComponentLookupError, getInterface, None, "bobesponja")
def getUtilities(iface): """Return all utility registrations that provide the interface.""" gsm = zapi.getGlobalSiteManager() for reg in gsm.registrations(): if not isinstance(reg, UtilityRegistration): continue if reg.provided.isOrExtends(iface): yield reg
def test_getLocalInterface_delegates_to_globalUtility(self): gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IInterface, Bar("blob"), name="blob") gsm.provideUtility(IBaz, Baz("global baz")) gsm.provideUtility(IInterface, Foo("global bob"), name="bob") self.assertEqual(getInterface(None, "bob").__class__, Foo) self.assertEqual(getInterface(None, "blob").__class__, Bar)
def items(self): """See zope.app.container.interfaces.IReadContainer""" sm = zapi.getGlobalSiteManager() items = [(encodeName(reg.name or NONAME), Utility(self, reg)) for reg in sm.registrations() if zapi.isinstance(reg, UtilityRegistration) and \ self.interface == reg.provided] items.sort() return items
def __call__(self): sm = zapi.getSiteManager() result = ('zapi.getSiteManager() is zapi.getGlobalSiteManager(): %s\n' 'IFiveUtilityRegistry.providedBy(utility_service): %s\n' 'isinstance(zapi.getSiteManager(), FiveSiteManager): %s' % (sm is zapi.getGlobalSiteManager(), IFiveUtilityRegistry.providedBy(sm.utilities), isinstance(sm, FiveSiteManager))) return result
def __call__(self): sm = zapi.getSiteManager() result = ('zapi.getSiteManager() is zapi.getGlobalSiteManager(): %s\n' 'IFiveUtilityRegistry.providedBy(utility_service): %s\n' 'isinstance(zapi.getSiteManager(), FiveSiteManager): %s' % (sm is zapi.getGlobalSiteManager(), IFiveUtilityRegistry.providedBy( sm.utilities), isinstance(sm, FiveSiteManager))) return result
def test_ServerControlView(self): control = ServerControlStub() zapi.getGlobalSiteManager().provideUtility(IServerControl, control) test_serverctrl = self._TestView__newView( applicationController, {'shutdown': 1, 'time': 100}, ) test_serverctrl.action() self.assertEqual(control.did_shutdown, 100) test_serverctrl = self._TestView__newView( applicationController, {'restart': 1, 'time': 100}, ) test_serverctrl.action() self.assertEqual(control.did_restart, 100)
def test_globalsearchInterface_delegates_to_globalUtility(self): foo = Foo("global bob") bar = Bar("global") baz = Baz("global baz") gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IInterface, bar) gsm.provideUtility(IBaz, baz) gsm.provideUtility(IInterface, foo, name="bob") self.assertEqual(searchInterface(None, search_string="bob"), [foo])
def __call__(self): sm = zapi.getSiteManager() result = { 'zapi.getSiteManager() is zapi.getGlobalSiteManager()': sm is zapi.getGlobalSiteManager(), 'IFiveUtilityRegistry.providedBy(utility_service)': IFiveUtilityRegistry.providedBy(sm.utilities), 'isinstance(zapi.getSiteManager(), FiveSiteManager)': isinstance(sm, FiveSiteManager), } return pprint.pformat(result)
def get(self, key, default=None): """See zope.app.container.interfaces.IReadContainer""" sm = zapi.getGlobalSiteManager() key = decodeName(key) if key == NONAME: key = '' utils = [Utility(self, reg) for reg in sm.registrations() if zapi.isinstance(reg, UtilityRegistration) and \ reg.name == key and reg.provided == self.interface] return utils and utils[0] or default
def registerHelpTopic(self, parent_path, id, title, doc_path, interface=None, view=None, class_=None, resources=None): "See zope.app.onlineHelp.interfaces.IOnlineHelp" if not os.path.exists(doc_path): raise ConfigurationError( "Help Topic definition %s does not exist" % doc_path ) if class_ is None: class_ = OnlineHelpTopic # Create topic base on the custom class or OnlinHelpTopic topic = class_(id, title, doc_path, parent_path, interface, view) # add resources to topic if resources is not None: topic.addResources(resources) # add topic to onlinehelp hierarchy parent = None try: parent = zapi.traverse(self, parent_path) parent[id] = topic except KeyError: pass for t in zapi.getUtilitiesFor(IOnlineHelpTopic): if parent is None: if t[1].getTopicPath() == parent_path: t[1][id] = topic if topic.getTopicPath() == t[1].parentPath: topic[t[1].id] = t[1] # Add topic to utilities registry #utils = zapi.getService(Utilities) #utils.provideUtility(IOnlineHelpTopic, topic, topic.getTopicPath()) zapi.getGlobalSiteManager().provideUtility( IOnlineHelpTopic, topic, topic.getTopicPath())
def addCheckerPublic(): """Add the CheckerPublic permission as 'zope.Public'""" perm = Permission('zope.Public', 'Public', """Special permission used for resources that are always public The public permission is effectively an optimization, sine it allows security computation to be bypassed. """ ) gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IPermission, perm, perm.id)
def queryNextSiteManager(context, default=None): """Get the next site manager. If the site manager of the given context is the global site manager, then `default` is returned. """ sm = zapi.getSiteManager(context) if zope.component.site.IGlobalSiteManager.providedBy(sm): return default if sm.next is None: return zapi.getGlobalSiteManager() return sm.next
def getViews(iface, type=IRequest): """Get all view registrations for a particular interface.""" gsm = zapi.getGlobalSiteManager() for reg in gsm.registrations(): if (isinstance(reg, AdapterRegistration) and len(reg.required) > 0 and reg.required[-1] is not None and reg.required[-1].isOrExtends(type)): for required_iface in reg.required[:-1]: if required_iface is None or iface.isOrExtends(required_iface): yield reg
def test_query_get_Utility_delegates_to_global(self): gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IInterface, Foo("global")) gsm.provideUtility(IInterface, Foo("global bob"), name="bob") sm = zapi.getSiteManager(self.rootFolder) self.assert_(gsm != sm) # If queryUtility works on the site manager, getUtility in zapi must # also work. self.assertEqual(sm.queryUtility(IInterface).foo(), "foo global") self.assertEqual(sm.queryUtility(IInterface, "bob").foo(), "foo global bob")
def _checkViewFor(for_=None, layer=None, view_name=None): """Check if there is a view of that name registered for IAdding and IBrowserRequest. If not raise a ConfigurationError It will raise a ConfigurationError if : o view="" o if view_name is not registred """ if view_name is None: raise ConfigurationError("Within a addMenuItem directive the view attribut" " is optional but can't be empty") gsm = zapi.getGlobalSiteManager() if gsm.adapters.lookup((for_, layer), Interface, view_name) is None: raise ConfigurationError("view name %s not found " % view_name)
def searchInterfaceUtilities(context, search_string=None, base=None): gsm = zapi.getGlobalSiteManager() iface_utilities = gsm.getUtilitiesFor(IInterface) if search_string: search_string = search_string.lower() iface_utilities = [iface_util for iface_util in iface_utilities if (getInterfaceAllDocs(iface_util[1]).\ find(search_string) >= 0)] if base: res = [iface_util for iface_util in iface_utilities if iface_util[1].extends(base)] else: res = [iface_util for iface_util in iface_utilities] return res
def SiteManagerAdapter(ob): """An adapter from ILocation to ISiteManager. The ILocation is interpreted flexibly, we just check for ``__parent__``. """ current = ob while True: if interfaces.ISite.providedBy(current): return current.getSiteManager() current = getattr(current, '__parent__', None) if current is None: # It is not a location or has no parent, so we return the global # site manager return zapi.getGlobalSiteManager()
def getFactories(iface): """Return the factory registrations, who will return objects providing this interface.""" gsm = zapi.getGlobalSiteManager() for reg in gsm.registrations(): if not isinstance(reg, UtilityRegistration): continue if reg.provided is not IFactory: continue interfaces = reg.component.getInterfaces() try: if interfaces.isOrExtends(iface): yield reg except AttributeError: for interface in interfaces: if interface.isOrExtends(iface): yield reg break
def getProvidedAdapters(iface, withViews=False): """Get adapter registrations where this interface is provided.""" gsm = zapi.getGlobalSiteManager() for reg in gsm.registrations(): # Only get adapters if not isinstance(reg, (AdapterRegistration, SubscriptionRegistration)): continue # Ignore adapters that have no required interfaces if len(reg.required) == 0: continue # Ignore views if not withViews and reg.required[-1] and \ reg.required[-1].isOrExtends(IRequest): continue # Only get adapters for which this interface is provided if reg.provided is None or not reg.provided.isOrExtends(iface): continue yield reg
def testDefaultView(self): ob = Ob() self.assertEqual( zapi.queryMultiAdapter((Ob(), Request(IV)), name='test'), None) xmlconfig(StringIO(template % ( ''' <defaultView name="test" for="zope.app.component.tests.views.IC" type="zope.app.component.tests.views.IV"/> ''' ))) self.assertEqual( zapi.queryMultiAdapter((Ob(), Request(IV)), name='test'), None) self.assertEqual( zapi.getGlobalSiteManager().adapters.lookup((IC, IV), IDefaultViewName), 'test')
def test_localInterfaceitems_filters_only_interfaces(self): bar = Bar("global") baz = Baz("global baz") foo = Foo("global bob") gsm = zapi.getGlobalSiteManager() gsm.provideUtility(IInterface, foo, name="bob") gsm.provideUtility(ILocalUtility, bar) gsm.provideUtility(IBaz, baz) iface_utilities = gsm.getUtilitiesFor(IInterface) ifaces = [iface for (name, iface) in iface_utilities] self.assertEqual(ifaces, [(foo)]) iface_utilities = gsm.getUtilitiesFor(ILocalUtility) ifaces = [iface for (name, iface) in iface_utilities] self.assertEqual(ifaces, [(bar)]) iface_utilities = gsm.getUtilitiesFor(IBaz) ifaces = [iface for (name, iface) in iface_utilities] self.assertEqual(ifaces, [(baz)])
def __init__(self, site): # Locate the site manager self.__parent__ = site self.__name__ = '++etc++site' # Make sure everything is setup correctly BTreeContainer.__init__(self) # Set up adapter registries gsm = zapi.getGlobalSiteManager() self.adapters = adapter.LocalAdapterRegistry(gsm.adapters) self.utilities = LocalUtilityRegistry(gsm.utilities) # Setup located registry attributes next = _findNextSiteManager(site) self.setNext(next) # Setup default site management folder folder = SiteManagementFolder() zope.event.notify(objectevent.ObjectCreatedEvent(folder)) self['default'] = folder