예제 #1
0
    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
예제 #2
0
 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'])
예제 #3
0
 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
예제 #4
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
 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
예제 #5
0
    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"])
예제 #6
0
    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'])
예제 #7
0
    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
예제 #8
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
    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
예제 #9
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
    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
예제 #10
0
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
예제 #11
0
파일: context.py 프로젝트: calston/tums
    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
예제 #12
0
    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
예제 #13
0
파일: context.py 프로젝트: calston/tums
    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
예제 #14
0
    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
예제 #15
0
    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
예제 #16
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
    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
예제 #17
0
    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
예제 #18
0
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
예제 #19
0
 def __repr__(self):
     if self.iface is not None:
         return "%s(interface=%s)" % (self.__class__.__name__, util.qual(self.iface))
     return self.__class__.__name__ + "()"
예제 #20
0
 def setComponent(self, interfaceClass, component):
     """
     """
     if hasattr(component, "__class__"):
         fixClassImplements(component.__class__)
     self._adapterCache[util.qual(interfaceClass)] = component
예제 #21
0
 def to_string(self):
     if not self.convert_to:
         raise NotImplementedError("Implement in %s" %
                                   util.qual(self.__class__))
     return self.convert_to()
예제 #22
0
def megaGetInterfaces(adapter):
    return [qual(x) for x in providedBy(adapter)]
예제 #23
0
파일: context.py 프로젝트: Rafav/iteexe
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
예제 #24
0
 def __repr__(self):
     if self.interface is not None:
         return "Table(interface=%s)" % util.qual(self.interface)
     return "Table()"
예제 #25
0
파일: annotate.py 프로젝트: Rafav/iteexe
 def __repr__(self):
     if self.interface is None:
         return "Object(None)"
     return "Object(interface=%s)" % util.qual(self.interface)
예제 #26
0
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
예제 #27
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
 def setComponent(self, interfaceClass, component):
     """
     """
     self._adapterCache[qual(interfaceClass)] = component
예제 #28
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
 def __init__(self, adapterCache=None):
     self._adapterCache = A = {}
     if adapterCache:
         for k, v in adapterCache.items():
             A[qual(k)] = v
예제 #29
0
 def __init__(self, adapterCache=None):
     self._adapterCache = A = {}
     if adapterCache:
         for k, v in adapterCache.items():
             A[qual(k)] = v
예제 #30
0
 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)
예제 #31
0
 def coerce(self, val, configurable):
     raise NotImplementedError, "Implement in %s" % util.qual(
         self.__class__)
예제 #32
0
 def __repr__(self):
     if self.interface is None:
         return "Object(None)"
     return "Object(interface=%s)" % util.qual(self.interface)
예제 #33
0
 def __repr__(self):
     if self.iface is not None:
         return "%s(interface=%s)" % (self.__class__.__name__,
                                      util.qual(self.iface))
     return self.__class__.__name__ + "()"
예제 #34
0
 def configure(self, boundTo, results):
     raise NotImplementedError, "Implement in %s" % util.qual(
         self.__class__)
예제 #35
0
파일: context.py 프로젝트: calston/tums
def megaGetInterfaces(adapter):
    return [qual(x) for x in providedBy(adapter)]
예제 #36
0
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):
예제 #37
0
 def unsetComponent(self, interfaceClass):
     """Remove my component specified by the given interface class."""
     del self._adapterCache[util.qual(interfaceClass)]
예제 #38
0
파일: annotate.py 프로젝트: Rafav/iteexe
 def configure(self, boundTo, results):
     raise NotImplementedError, "Implement in %s" % util.qual(self.__class__)
예제 #39
0
 def setComponent(self, interfaceClass, component):
     """
     """
     self._adapterCache[qual(interfaceClass)] = component
예제 #40
0
파일: annotate.py 프로젝트: Rafav/iteexe
 def coerce(self, val, configurable):
     raise NotImplementedError, "Implement in %s" % util.qual(self.__class__)
예제 #41
0
파일: context.py 프로젝트: calston/tums
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)
예제 #42
0
파일: annotate.py 프로젝트: Rafav/iteexe
 def __repr__(self):
     if self.interface is not None:
         return "Table(interface=%s)" % util.qual(self.interface)
     return "Table()"
예제 #43
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
 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
예제 #44
0
파일: compy.py 프로젝트: UstadMobile/eXePUB
 def unsetComponent(self, interfaceClass):
     """Remove my component specified by the given interface class."""
     del self._adapterCache[qual(interfaceClass)]
예제 #45
0
 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