def __call__(self, adaptable, default=_Nothing, persist=None, registry=None): """ Try to adapt `adaptable' to self; return `default' if it was passed, otherwise raise L{CannotAdapt}. """ adapter = default registry = getRegistry(registry) ## getComponent check for cross-compatibility with twisted Componentized if implements(adaptable, IComponentized) or getattr(adaptable, 'getComponent', None): adapter = adaptable.getComponent(self, registry, default=_NoImplementor) if adapter is default or adapter is _NoImplementor: adapter = registry.getAdapter( adaptable, self, _NoImplementor, persist=persist) if adapter is _NoImplementor: if getattr(self, '__adapt__', None): adapter = self.__adapt__.im_func(adaptable, default) else: adapter = default if adapter is _Nothing: if getattr(adaptable, '__class__', None): t = qual(adaptable.__class__) else: t = qual(type(adaptable)) raise CannotAdapt("%s (type %s) cannot be adapted to %s." % (adaptable, t, self)) return adapter
def test_handlerWithIdentifier(self): gatherer = LiveGatherer() ctx = context.WovenContext() ctx.remember(gatherer, livepage.IClientHandle) oneQual = util.qual(oneHandler) twoQual = util.qual(twoHandler) livepage.handler(oneHandler, identifier='same')(ctx, None) livepage.handler(twoHandler, identifier='same')(ctx, None) gatherer.handleInput('same') self.assertEquals(gatherer.heard, ['one', 'two'])
def getAdapterFactory(self, fromInterface, toInterface, default): """Return registered adapter for a given class and interface. """ R = self.adapterRegistry.get((fromInterface, toInterface), None) if R is None: adapterQual = self.adapterRegistry.get((qual(fromInterface), qual(toInterface)), None) if adapterQual is None: return default R = namedAny(adapterQual) R.__implements__ = tupleTreeToList(getattr(R, '__implements__', ())) self.adapterRegistry[(fromInterface, toInterface)] = R return R
def getAdapterFactory(self, fromInterface, toInterface, default): """Return registered adapter for a given class and interface. """ R = self.adapterRegistry.get((fromInterface, toInterface), None) if R is None: adapterQual = self.adapterRegistry.get( (qual(fromInterface), qual(toInterface)), None) if adapterQual is None: return default R = namedAny(adapterQual) R.__implements__ = tupleTreeToList(getattr(R, '__implements__', ())) self.adapterRegistry[(fromInterface, toInterface)] = R return R
def test_handlerWithIdentifier(self): gatherer = LiveGatherer() ctx = context.WovenContext() ctx.remember(gatherer, livepage.IClientHandle) oneQual = util.qual(oneHandler) twoQual = util.qual(twoHandler) ## Subscribe both handlers to the same identifier livepage.handler(oneHandler, identifier="same")(ctx, None) livepage.handler(twoHandler, identifier="same")(ctx, None) gatherer.handleInput("same") self.assertEquals(gatherer.heard, ["one", "two"])
def test_handlerWithIdentifier(self): gatherer = LiveGatherer() ctx = context.WovenContext() ctx.remember(gatherer, livepage.IClientHandle) oneQual = util.qual(oneHandler) twoQual = util.qual(twoHandler) ## Subscribe both handlers to the same identifier livepage.handler(oneHandler, identifier='same')(ctx, None) livepage.handler(twoHandler, identifier='same')(ctx, None) gatherer.handleInput('same') self.assertEquals(gatherer.heard, ['one', 'two'])
def getComponent(self, interface, registry=None, default=None): """Create or retrieve an adapter for the given interface. If such an adapter has already been created, retrieve it from the cache that this instance keeps of all its adapters. Adapters created through this mechanism may safely store system-specific state. If you want to register an adapter that will be created through getComponent, but you don't require (or don't want) your adapter to be cached and kept alive for the lifetime of this Componentized object, set the attribute 'temporaryAdapter' to True on your adapter class. If you want to automatically register an adapter for all appropriate interfaces (with addComponent), set the attribute 'multiComponent' to True on your adapter class. """ registry = getRegistry(registry) k = util.qual(interface) if self._adapterCache.has_key(k): return self._adapterCache[k] else: adapter = interface.__adapt__(self) if hasattr(adapter, "__class__"): fixClassImplements(adapter.__class__) if adapter is not None and adapter is not _Nothing and not ( hasattr(adapter, "temporaryAdapter") and adapter.temporaryAdapter): self._adapterCache[k] = adapter if (hasattr(adapter, "multiComponent") and adapter.multiComponent): self.addComponent(adapter) return adapter
def getComponent(self, interface, registry=None, default=None): """Create or retrieve an adapter for the given interface. If such an adapter has already been created, retrieve it from the cache that this instance keeps of all its adapters. Adapters created through this mechanism may safely store system-specific state. If you want to register an adapter that will be created through getComponent, but you don't require (or don't want) your adapter to be cached and kept alive for the lifetime of this Componentized object, set the attribute 'temporaryAdapter' to True on your adapter class. If you want to automatically register an adapter for all appropriate interfaces (with addComponent), set the attribute 'multiComponent' to True on your adapter class. """ registry = getRegistry(registry) k = qual(interface) if self._adapterCache.has_key(k): return self._adapterCache[k] elif implements(self, interface): return self else: adapter = registry.getAdapter( self, interface, default, lambda k, ik, d: self.locateAdapterClass(k, ik, d, registry)) if adapter is not None and adapter is not _Nothing and not ( getattr(adapter, "temporaryAdapter", None) and adapter.temporaryAdapter): self._adapterCache[k] = adapter if (getattr(adapter, "multiComponent", None) and adapter.multiComponent and getattr(adapter, '__implements__', None)): self.addComponent(adapter) return adapter
def __call__(self, adaptable, default=_Nothing, persist=None, registry=None): """ Try to adapt `adaptable' to self; return `default' if it was passed, otherwise raise L{CannotAdapt}. """ adapter = default registry = getRegistry(registry) ## getComponent check for cross-compatibility with twisted Componentized if implements(adaptable, IComponentized) or getattr( adaptable, 'getComponent', None): adapter = adaptable.getComponent(self, registry, default=_NoImplementor) if adapter is default or adapter is _NoImplementor: adapter = registry.getAdapter(adaptable, self, _NoImplementor, persist=persist) if adapter is _NoImplementor: if getattr(self, '__adapt__', None): adapter = self.__adapt__.im_func(adaptable, default) else: adapter = default if adapter is _Nothing: if getattr(adaptable, '__class__', None): t = qual(adaptable.__class__) else: t = qual(type(adaptable)) raise CannotAdapt("%s (type %s) cannot be adapted to %s." % (adaptable, t, self)) return adapter
def getFlattener(original): """Get a flattener function with signature (ctx, original) for the object original. """ if hasattr(original, '__class__'): klas = original.__class__ else: klas = type(original) fromInterfaces = compy.getInterfaces(klas) + [klas] for inter in fromInterfaces: adapter = _flatteners.get(inter, None) if adapter is not None: return adapter interQual = util.qual(inter) adapterQual = _lazy_flatteners.get(interQual, None) if adapterQual is not None: adapter = util.namedAny(adapterQual) registerFlattener(adapter, inter) del _lazy_flatteners[interQual] return adapter print "***", fromInterfaces
def remember(self, adapter, interface=None): """Remember an object that implements some interfaces. Later, calls to .locate which are passed an interface implemented by this object will return this object. If the 'interface' argument is supplied, this object will only be remembered for this interface, and not any of the other interfaces it implements. """ if interface is None: interfaceList = megaGetInterfaces(adapter) if not interfaceList: interfaceList = [dataqual] else: interfaceList = [qual(interface)] if self._remembrances is None: self._remembrances = {} for interface in interfaceList: self._remembrances[interface] = adapter return self
def locate(self, interface, depth=1, _default=object()): """Locate an object which implements a given interface. Objects will be searched through the context stack top down. """ key = qual(interface) currentContext = self while True: if depth < 0: full = [] while True: try: full.append(self.locate(interface, len(full)+1)) except KeyError: break #print "full", full, depth if full: return full[depth] return None _remembrances = currentContext._remembrances if _remembrances is not None: rememberedValue = _remembrances.get(key, _default) if rememberedValue is not _default: depth -= 1 if not depth: return rememberedValue # Hook for FactoryContext and other implementations of complex locating locateHook = currentContext.locateHook if locateHook is not None: result = locateHook(interface) if result is not None: currentContext.remember(result, interface) return result contextParent = currentContext.parent if contextParent is None: raise KeyError, "Interface %s was not remembered." % key currentContext = contextParent
def addComponent(self, component, ignoreClass=0, registry=None): """ Add a component to me, for all appropriate interfaces. In order to determine which interfaces are appropriate, the component's __implements__ attribute will be scanned. If the argument 'ignoreClass' is True, then all interfaces are considered appropriate. Otherwise, an 'appropriate' interface is one for which its class has been registered as an adapter for my class according to the rules of getComponent. @return: the list of appropriate interfaces """ for iface in tupleTreeToList(component.__implements__): if (ignoreClass or (self.locateAdapterClass(self.__class__, iface, None, registry) == component.__class__)): self._adapterCache[qual(iface)] = component
def addComponent(self, component, ignoreClass=0, registry=None): """ Add a component to me, for all appropriate interfaces. In order to determine which interfaces are appropriate, the component's provided interfaces will be scanned. If the argument 'ignoreClass' is True, then all interfaces are considered appropriate. Otherwise, an 'appropriate' interface is one for which its class has been registered as an adapter for my class according to the rules of getComponent. @return: the list of appropriate interfaces """ if hasattr(component, "__class__"): fixClassImplements(component.__class__) for iface in declarations.providedBy(component): if (ignoreClass or (self.locateAdapterClass(self.__class__, iface, None, registry) == component.__class__)): self._adapterCache[util.qual(iface)] = component
def getFlattener(original): """Get a flattener function with signature (ctx, original) for the object original. """ if hasattr(original, '__class__'): klas = original.__class__ else: klas = type(original) fromInterfaces = compy.getInterfaces(klas) + [klas] for inter in fromInterfaces: adapter = _flatteners.get(inter, None) if adapter is not None: return adapter interQual = util.qual(inter) adapterQual = _lazy_flatteners.get(interQual, None) if adapterQual is not None: adapter = util.namedAny(adapterQual) registerFlattener(adapter, inter) #for fromInter in fromInterfaces: # registerFlattener(adapter, fromInter) del _lazy_flatteners[interQual] return adapter print "***", fromInterfaces
def __repr__(self): if self.iface is not None: return "%s(interface=%s)" % (self.__class__.__name__, util.qual(self.iface)) return self.__class__.__name__ + "()"
def setComponent(self, interfaceClass, component): """ """ if hasattr(component, "__class__"): fixClassImplements(component.__class__) self._adapterCache[util.qual(interfaceClass)] = component
def to_string(self): if not self.convert_to: raise NotImplementedError("Implement in %s" % util.qual(self.__class__)) return self.convert_to()
def megaGetInterfaces(adapter): return [qual(x) for x in providedBy(adapter)]
def megaGetInterfaces(adapter): adrs = [qual(x) for x in compy.getInterfaces(adapter)] ## temporarily turn this off till we need it if False: #hasattr(adapter, '_adapterCache'): adrs.extend(adapter._adapterCache.keys()) return adrs
def __repr__(self): if self.interface is not None: return "Table(interface=%s)" % util.qual(self.interface) return "Table()"
def __repr__(self): if self.interface is None: return "Object(None)" return "Object(interface=%s)" % util.qual(self.interface)
def setComponent(self, interfaceClass, component): """ """ self._adapterCache[qual(interfaceClass)] = component
def __init__(self, adapterCache=None): self._adapterCache = A = {} if adapterCache: for k, v in adapterCache.items(): A[qual(k)] = v
def from_string(self, string): if not self.convert_from: raise NotImplementedError("Implement in %s" % util.qual(self.__class__)) self.value = self.convert_from(string)
def coerce(self, val, configurable): raise NotImplementedError, "Implement in %s" % util.qual( self.__class__)
def configure(self, boundTo, results): raise NotImplementedError, "Implement in %s" % util.qual( self.__class__)
from __future__ import generators import warnings from nevow import stan from nevow.inevow import IData, IRequest from nevow.stan import Unset from nevow.util import qual from zope.interface import providedBy # TTT: Move to web2.context def megaGetInterfaces(adapter): return [qual(x) for x in providedBy(adapter)] dataqual = qual(IData) class WebContext(object): _remembrances = None tag = None _slotData = None parent = None locateHook = None # XXX: can we get rid of these somehow? isAttrib = property(lambda self: False) inURL = property(lambda self: False) inJS = property(lambda self: False) inJSSingleQuoteString = property(lambda self: False) precompile = property(lambda self: False) def with(self, tag):
def unsetComponent(self, interfaceClass): """Remove my component specified by the given interface class.""" del self._adapterCache[util.qual(interfaceClass)]
def configure(self, boundTo, results): raise NotImplementedError, "Implement in %s" % util.qual(self.__class__)
def coerce(self, val, configurable): raise NotImplementedError, "Implement in %s" % util.qual(self.__class__)
from __future__ import generators import warnings from nevow import stan from nevow.inevow import IData, IRequest from nevow.stan import Unset from nevow.util import qual from zope.interface import providedBy # TTT: Move to web2.context def megaGetInterfaces(adapter): return [qual(x) for x in providedBy(adapter)] dataqual = qual(IData) class WebContext(object): _remembrances = None tag = None _slotData = None parent = None locateHook = None # XXX: can we get rid of these somehow? isAttrib = property(lambda self: False) inURL = property(lambda self: False) inJS = property(lambda self: False) inJSSingleQuoteString = property(lambda self: False) precompile = property(lambda self: False)
def upgradeToVersion1(self): # To let Componentized instances interact correctly with # rebuild(), we cannot use class objects as dictionary keys. for (k, v) in self._adapterCache.items(): self._adapterCache[qual(k)] = v
def unsetComponent(self, interfaceClass): """Remove my component specified by the given interface class.""" del self._adapterCache[qual(interfaceClass)]