예제 #1
0
    def __get__(self, inst, cls=None):
        if inst is None:
            return getObjectSpecification(cls)

        request = getRequest()
        annotations = IAnnotations(request)

        # Return cached spec from request
        if inst.__parent__ is not None and inst.__name__ is not None:
            digest = inst.__parent__.schema_digest
            key = '.'.join([self.__class__.__name__, digest, inst.__name__])
            spec = annotations.get(key)
            if spec is not None:
                return spec

            spec = getattr(inst, '__provides__', None)
            if spec is None:
                spec = implementedBy(cls)

            model = load_model(
                aq_base(inst.__parent__).schema,
                cache_key=inst.__parent__.schema_digest,
            )
            schemata = []
            for schema in [
                    model.schemata[name] for name in model.schemata
                    if name == u'' or IS_TRANSLATION.match(name)
            ]:
                try:
                    field = schema[inst.__name__]
                except AttributeError:
                    continue
                try:
                    schemata.append(field.schema)
                except AttributeError:
                    schemata.append(field.value_type.schema)
            schemata.append(spec)

            spec = Implements(*schemata)

            # Cache spec into request
            annotations[key] = spec

        else:

            spec = getattr(inst, '__provides__', None)
            if spec is None:
                spec = implementedBy(cls)

            # Set by FlowSubmissionDataFactory
            schemata = [inst._v_initial_schema, spec]

            spec = Implements(*schemata)

        return spec
예제 #2
0
def _getAdapterRequired(factory, required):
    if required is None:
        try:
            required = factory.__component_adapts__
        except AttributeError:
            raise TypeError(
                "The adapter factory doesn't have a __component_adapts__ "
                "attribute and no required specifications were specified"
                )
    elif ISpecification.providedBy(required):
        raise TypeError("the required argument should be a list of "
                        "interfaces, not a single interface")

    result = []
    for r in required:
        if r is None:
            r = Interface
        elif not ISpecification.providedBy(r):
            if isinstance(r, class_types):
                r = implementedBy(r)
            else:
                raise TypeError("Required specification must be a "
                                "specification or class."
                                )
        result.append(r)
    return tuple(result)
예제 #3
0
def _getAdapterProvided(factory):
    provided = list(implementedBy(factory))
    if len(provided) == 1:
        return provided[0]
    raise TypeError(
        "The adapter factory doesn't implement a single interface "
        "and no provided interface was specified.")
예제 #4
0
    def implementedBy(self, cls):
        """Test whether the specification is implemented by a class or factory.

        Raise TypeError if argument is neither a class nor a callable.
        """
        spec = implementedBy(cls)
        return self in spec._implied
예제 #5
0
def _getAdapterProvided(factory):
    provided = list(implementedBy(factory))
    if len(provided) == 1:
        return provided[0]
    raise TypeError(
        "The adapter factory doesn't implement a single interface "
        "and no provided interface was specified.")
예제 #6
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        # Find the cached value.
        cache = getattr(inst, "_v__providedBy__", None)

        # Find the data we need to know if our cache needs to be invalidated
        provided = link_provides = getattr(inst._context, "__provides__", None)

        # See if we have a valid cache, and if so return it
        if cache is not None:
            cached_mtime, cached_provides, cached_provided = cache

            if inst._p_mtime == cached_mtime and link_provides is cached_provides:
                return cached_provided

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if provided is None:
            provided = implementedBy(cls)

        # Add the interfaces provided by the target, but ensure that some problematic
        # interfaces are removed
        provided += providedBy(
            inst._context) - IIterateAware - IVersioningSupport
        provided += ISymlinkMarker

        inst._v__providedBy__ = inst._p_mtime, link_provides, provided
        return provided
예제 #7
0
    def __get__(self, inst, cls=None):
        if inst is None:
            return getObjectSpecification(cls)

        tp = inst.__type__
        cached = getattr(tp, '_v__providedBy', _marker)
        if cached is not _marker:
            return cached

        provided = [implementedBy(inst.__class__)]
        bhreg = AdapterRegistry()
        for behavior in tp.behaviors:
            behavior = queryBehavior(behavior)
            if behavior is not None:
                bhreg.register((), behavior.spec, '', behavior)
                provided.append(behavior.spec)

        schreg = AdapterRegistry()
        for schId in tp.schemas:
            sch = querySchema(schId)
            if sch is not None and sch.spec not in provided:
                schreg.register((), sch.spec, '', sch)
                provided.append(sch.spec)

        spec = Implements(*provided)

        tp._v__providedBy = spec
        tp._v__bhCache = bhreg
        tp._v__schCache = schreg

        return spec
예제 #8
0
    def implementedBy(self, cls):
        """Test whether the specification is implemented by a class or factory.

        Raise TypeError if argument is neither a class nor a callable.
        """
        spec = implementedBy(cls)
        return self in spec._implied
예제 #9
0
 def __get__(self, inst, cls=None):
     global generated
     if inst is None:
         return getObjectSpecification(cls)
     spec = getattr(inst, '__provides__', None)
     if spec is None:
         spec = implementedBy(cls)
     signature = getattr(inst, 'signature', None)
     if signature is None:
         return spec
     if not ismd5hex(signature):
         if not isdottedname(signature):
             return spec
         # not an md5 signature, so perhaps we have a dotted name
         try:
             iface = resolve(signature)
             if not IInterface.providedBy(iface):
                 raise ValueError('Not interface: %s' % signature)
             return Implements(iface, spec)
         except ImportError:
             logger.warning('SignatureAwareDescriptor: '
                            'unabled to resolve interface '
                            '%s by dotted name.')
             return spec
     iface_name = 'I%s' % signature
     dynamic = [getattr(generated, iface_name)]
     dynamic.append(spec)
     spec = Implements(*dynamic)
     return spec
예제 #10
0
 def __get__(self, inst, cls=None):
     global generated
     if inst is None:
         return getObjectSpecification(cls)
     spec = getattr(inst, '__provides__', None)
     if spec is None:
         spec = implementedBy(cls)
     signature = getattr(inst, 'signature', None)
     if signature is None:
         return spec
     if not ismd5hex(signature):
         if not isdottedname(signature):
             return spec
         # not an md5 signature, so perhaps we have a dotted name
         try:
             iface = resolve(signature)
             if not IInterface.providedBy(iface):
                 raise ValueError('Not interface: %s' % signature)
             return Implements(iface, spec)
         except ImportError:
             logger.warning('SignatureAwareDescriptor: '
                            'unabled to resolve interface '
                            '%s by dotted name.')
             return spec
     iface_name = 'I%s' % signature
     dynamic = [getattr(generated, iface_name)]
     dynamic.append(spec)
     spec = Implements(*dynamic)
     return spec
예제 #11
0
def _getAdapterRequired(factory, required):
    if required is None:
        try:
            required = factory.__component_adapts__
        except AttributeError:
            raise TypeError(
                "The adapter factory doesn't have a __component_adapts__ "
                "attribute and no required specifications were specified"
                )
    elif ISpecification.providedBy(required):
        raise TypeError("the required argument should be a list of "
                        "interfaces, not a single interface")

    result = []
    for r in required:
        if r is None:
            r = Interface
        elif not ISpecification.providedBy(r):
            if isinstance(r, CLASS_TYPES):
                r = implementedBy(r)
            else:
                raise TypeError("Required specification must be a "
                                "specification or class."
                                )
        result.append(r)
    return tuple(result)
예제 #12
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        # Find the data we need to know if our cache needs to be invalidated
        direct_spec = getattr(inst, '__provides__', None)
        portal_type = getattr(inst, 'portal_type', None)

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        fti = queryUtility(IDexterityFTI, name=portal_type)
        if fti is None:
            return spec

        schema = SCHEMA_CACHE.get(portal_type)
        subtypes = SCHEMA_CACHE.subtypes(portal_type)

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)
        updated = inst._p_mtime, schema, subtypes, direct_spec

        # See if we have a valid cache. Reasons to do this include:
        #
        #  - The schema was modified.
        #  - The subtypes were modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        if cache is not None:
            cached_mtime, cached_schema, cached_subtypes, \
                cached_direct_spec, cached_spec = cache

            if cache[:-1] == updated:
                return cached_spec

        dynamically_provided = [] if schema is None else [schema]
        dynamically_provided.extend(subtypes)

        # If we have neither a schema, nor a subtype, then we're also done.
        if not dynamically_provided:
            return spec

        dynamically_provided.append(spec)
        spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (spec, )

        return spec
예제 #13
0
    def test_impl(self):
        myTask = MyTask()
#         print CabbageTask.implementedBy(MyTask)
#         print directlyProvides(myTask,Task)
        print type(MyTask)
        print list(providedBy(myTask))[0]
        print list(implementedBy(MyTask))
        myTask.run()
        pass
예제 #14
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)
        
        # Find the data we need to know if our cache needs to be invalidated
        direct_spec = getattr(inst, '__provides__', None)
        portal_type = getattr(inst, 'portal_type', None)
        
        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        fti = queryUtility(IDexterityFTI, name=portal_type)
        if fti is None:
            return spec

        schema = SCHEMA_CACHE.get(portal_type)
        subtypes = SCHEMA_CACHE.subtypes(portal_type)

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)
        updated = inst._p_mtime, schema, subtypes, direct_spec

        # See if we have a valid cache. Reasons to do this include:
        #
        #  - The schema was modified.
        #  - The subtypes were modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        if cache is not None:
            cached_mtime, cached_schema, cached_subtypes, \
                cached_direct_spec, cached_spec = cache

            if cache[:-1] == updated:
                return cached_spec

        dynamically_provided = [] if schema is None else [schema]
        dynamically_provided.extend(subtypes)

        # If we have neither a schema, nor a subtype, then we're also done.
        if not dynamically_provided:
            return spec

        dynamically_provided.append(spec)
        spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (spec, )

        return spec
예제 #15
0
    def setup(self, *args, **kwargs):
        super(ChatCommandPlugin, self).setup(*args, **kwargs)

        for name in dir(self):
            cls = getattr(self, name)
            try:
                if ICommand in implementedBy(cls):
                    log.info("Loading command {0}".format(cls.__name__))
                    self.commands.append(cls(self))
            except (DoesNotImplement, TypeError, AttributeError):
                pass
예제 #16
0
파일: interfaces.py 프로젝트: sgnn7/hamper
    def setup(self, *args, **kwargs):
        super(ChatCommandPlugin, self).setup(*args, **kwargs)

        for name in dir(self):
            cls = getattr(self, name)
            try:
                if ICommand in implementedBy(cls):
                    log.info("Loading command {0}".format(cls))
                    self.commands.append(cls(self))
            except (DoesNotImplement, TypeError, AttributeError):
                pass
예제 #17
0
파일: registry.py 프로젝트: mardiros/apium
def get(adapted_iface, original_iface=IDriver):
    """ Return registered adapter for a given class and interface. """

    if not isinstance(original_iface, interface.InterfaceClass):
        if hasattr(original_iface, '__class__'):
            original_iface = original_iface.__class__
        original_iface = declarations.implementedBy(original_iface)

    registred_type = _iface_registry.lookup1(original_iface, adapted_iface, '')
    if not registred_type:
        raise NotImplementedError('No implementation has been registered')
    return registred_type
예제 #18
0
def get(adapted_iface, original_iface=ICaliop):
    """ Return registered adapter for a given class and interface. """

    if not isinstance(original_iface, interface.InterfaceClass):
        if hasattr(original_iface, '__class__'):
            original_iface = original_iface.__class__
        original_iface = declarations.implementedBy(original_iface)

    registred_type = _iface_registry.lookup1(original_iface, adapted_iface, '')
    if not registred_type:
        raise NotImplementedError('No implementation has been registered')
    return registred_type
예제 #19
0
파일: registry.py 프로젝트: mardiros/aiorm
def get(adapted_iface, adapt=IDriver):
    """ Return registered adapter for a given class and interface. """

    if not isinstance(adapt, interface.InterfaceClass):
        if not inspect.isclass(adapt):
            adapt = adapt.__class__
        adapt = declarations.implementedBy(adapt)

    registred_type = _iface_registry.lookup1(adapt, adapted_iface, '')
    if not registred_type:
        raise NotImplementedError('No implementation has been registered')
    return registred_type
예제 #20
0
파일: registry.py 프로젝트: zeninpalm/aiorm
def get(adapted_iface, adapt=IDriver):
    """ Return registered adapter for a given class and interface. """

    if not isinstance(adapt, interface.InterfaceClass):
        if not inspect.isclass(adapt):
            adapt = adapt.__class__
        adapt = declarations.implementedBy(adapt)

    registred_type = _iface_registry.lookup1(adapt, adapted_iface, '')
    if not registred_type:
        raise NotImplementedError('No implementation has been registered')
    return registred_type
예제 #21
0
def getAdapterFactory(fromInterface, toInterface, default):
    """Return registered adapter for a given class and interface.

    Note that is tied to the *Twisted* global registry, and will
    thus not find adapters registered elsewhere.
    """
    self = globalRegistry
    if not isinstance(fromInterface, interface.InterfaceClass):
        fromInterface = declarations.implementedBy(fromInterface)
    factory = self.lookup1(fromInterface, toInterface)
    if factory is None:
        factory = default
    return factory
예제 #22
0
def getAdapterFactory(fromInterface, toInterface, default):
    """Return registered adapter for a given class and interface.

    Note that is tied to the *Twisted* global registry, and will
    thus not find adapters registered elsewhere.
    """
    self = globalRegistry
    if not isinstance(fromInterface, interface.InterfaceClass):
        fromInterface = declarations.implementedBy(fromInterface)
    factory = self.lookup1(fromInterface, toInterface)
    if factory is None:
        factory = default
    return factory
예제 #23
0
def getInterfaces(klass):
    """DEPRECATED. Return list of all interfaces the class implements. Or the object provides.
    This is horrible and stupid. Please use zope.interface.providedBy() or implementedBy().
    """
    warnings.warn("getInterfaces should not be used, use providedBy() or implementedBy()", ComponentsDeprecationWarning, stacklevel=2)
    if isinstance(klass, (type, types.ClassType)):
        fixClassImplements(klass)
        l = list(declarations.implementedBy(klass))
    else:
        fixClassImplements(klass.__class__)
        l = list(declarations.providedBy(klass))
    r = []
    for i in l:
        r.extend(superInterfaces(i))
    return util.uniquify(r)
예제 #24
0
파일: ten.py 프로젝트: perkinslr/nevow-py3
def registerFlattener(flattener, forType):
    """Register a function, 'flattener', which will be invoked when an object of type 'forType'
    is encountered in the stan dom. This function should return or yield strings, or objects
    for which there is also a flattener registered.
    
    flattener should take (original, ctx) where original is the object to flatten.
    """
    if type(flattener) is str or type(forType) is str:
        assert type(flattener) is str and type(forType) is str, "Must pass both strings or no strings to registerFlattener"
        flattener = util._namedAnyWithBuiltinTranslation(flattener)
        forType = util._namedAnyWithBuiltinTranslation(forType)

    if not isinstance(forType, interface.InterfaceClass):
        forType = declarations.implementedBy(forType)
        
    tpc.globalRegistry.register([forType], ISerializable, 'nevow.flat', flattener)
예제 #25
0
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.

    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
    __init__ method should accept one parameter, an instance implementing
    'origInterface'.
    """
    assert interfaceClasses, "You need to pass an Interface"

    # deal with class->interface adapters:
    if not isinstance(origInterface, InterfaceClass):
        origInterface = declarations.implementedBy(origInterface)
        
    for interfaceClass in interfaceClasses:
        globalRegistry.register([origInterface], interfaceClass, '', adapterFactory)
예제 #26
0
def backwardsCompatImplements(klass):
    """Make a class have __implements__, for backwards compatability.
    This allows you to use new zope.interface APIs for declaring
    implements on classes, while still allowing subclasses that
    expect the old API.
       class YourClass:
           zope.interface.implements(IFoo) # correct zope way
       backwardsCompatImplements(YourClass) # add __implements__
       ----
       class ThirdPartyClass(YourClass):
           __implements__ = IBar, YourClass.__implements__
    """
    for subclass in klass.__bases__:
        fixClassImplements(subclass)
    _fixedClasses[klass] = True # so fixClassImplements will skip it
    klass.__implements__ = _implementsTuple(declarations.implementedBy(klass))
예제 #27
0
def register_adapter(registry, adapter_factory, adapted, *interfaces):
    assert interfaces, "You need to pass an Interface"

    # deal with class->interface adapters:
    if not isinstance(adapted, interface.InterfaceClass):
        adapted_ = declarations.implementedBy(adapted)
    else:
        adapted_ = adapted

    for iface in interfaces:
        factory = registry.registered([adapted_], iface)
        if factory is not None:
            raise ValueError("an adapter (%s) was already registered." %
                             (factory, ))
    for iface in interfaces:
        registry.register([adapted_], iface, '', adapter_factory)

    return adapter_factory
예제 #28
0
def register_adapter(registry, adapter_factory, adapted, *interfaces):
    assert interfaces, "You need to pass an Interface"

    # deal with class->interface adapters:
    if not isinstance(adapted, interface.InterfaceClass):
        adapted_ = declarations.implementedBy(adapted)
    else:
        adapted_ = adapted

    for iface in interfaces:
        factory = registry.registered([adapted_], iface)
        if factory is not None:
            raise ValueError("an adapter (%s) was already registered."
                             % (factory, ))
    for iface in interfaces:
        registry.register([adapted_], iface, '', adapter_factory)

    return adapter_factory
예제 #29
0
def getInterfaces(klass):
    """DEPRECATED. Return list of all interfaces the class implements. Or the object provides.

    This is horrible and stupid. Please use zope.interface.providedBy() or implementedBy().
    """
    warnings.warn("getInterfaces should not be used, use providedBy() or implementedBy()", ComponentsDeprecationWarning, stacklevel=2)
    # try to support both classes and instances, giving different behaviour
    # which is HORRIBLE :(
    if isinstance(klass, (type, types.ClassType)):
        fixClassImplements(klass)
        l = list(declarations.implementedBy(klass))
    else:
        fixClassImplements(klass.__class__)
        l = list(declarations.providedBy(klass))
    r = []
    for i in l:
        r.extend(superInterfaces(i))
    return util.uniquify(r)
예제 #30
0
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.
    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
    __init__ method should accept one parameter, an instance implementing
    'origInterface'.
    """
    self = globalRegistry
    assert interfaceClasses, "You need to pass an Interface"
    global ALLOW_DUPLICATES
    if not isinstance(origInterface, interface.InterfaceClass):
        fixClassImplements(origInterface)
        origInterface = declarations.implementedBy(origInterface)
    for interfaceClass in interfaceClasses:
        factory = self.get(origInterface).selfImplied.get(interfaceClass, {}).get('')
        if (factory and not ALLOW_DUPLICATES):
            raise ValueError("an adapter (%s) was already registered." % (factory, ))
    for interfaceClass in interfaceClasses:
        self.register([origInterface], interfaceClass, '', adapterFactory)
예제 #31
0
def registerFlattener(flattener, forType):
    """Register a function, 'flattener', which will be invoked when an object of type 'forType'
    is encountered in the stan dom. This function should return or yield strings, or objects
    for which there is also a flattener registered.
    
    flattener should take (original, ctx) where original is the object to flatten.
    """
    if type(flattener) is str or type(forType) is str:
        assert type(flattener) is str and type(
            forType
        ) is str, "Must pass both strings or no strings to registerFlattener"
        flattener = util._namedAnyWithBuiltinTranslation(flattener)
        forType = util._namedAnyWithBuiltinTranslation(forType)

    if not isinstance(forType, interface.InterfaceClass):
        forType = declarations.implementedBy(forType)

    tpc.globalRegistry.register([forType], ISerializable, 'nevow.flat',
                                flattener)
    def __get__(self, inst, cls=None):

        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        # Find the cached value.
        cache = getattr(inst, '_v__providedBy__', None)

        # Find the data we need to know if our cache needs to be invalidated
        provided = alias_provides = getattr(inst, '__provides__', None)

        # See if we have a valid cache, and if so return it
        if cache is not None:
            cached_mtime, cached_provides, cached_provided = cache

            if (
                inst._p_mtime == cached_mtime and
                alias_provides is cached_provides
            ):
                return cached_provided

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if provided is None:
            assert cls == Alias # XXX: remove
            provided = implementedBy(cls)

        # Add the interfaces provided by the target
        target = aq_base(inst._target)
        if target is None:
            return provided # don't cache yet!

        # Add the interfaces provided by the target, but take away
        # IHasAlias if set
        provided += providedBy(target) - IHasAlias - IIterateAware

        if ITranslatable:
            provided -= ITranslatable

        inst._v__providedBy__ = inst._p_mtime, alias_provides, provided
        return provided
예제 #33
0
파일: registry.py 프로젝트: mardiros/aiorm
def register(registred_type, *adapted_ifaces, adapt=IDriver):
    """ Register an adapter class for an original interface that implement
    adapted_ifaces. """
    assert registred_type, 'You need to pass an Interface'

    # deal with class->interface adapters:
    if not isinstance(adapt, interface.InterfaceClass):
        adapt = declarations.implementedBy(adapt)

    if not adapted_ifaces:
        adapted_ifaces = implementedBy(registred_type)

    for iface in adapted_ifaces:
        factory = _iface_registry.registered([adapt], iface)
        if factory is not None:
            raise ValueError('An adapter ({}) was already registered.'
                             'for iface {}'.format(factory, iface))

    for iface in adapted_ifaces:
        _iface_registry.register([adapt], iface, '', registred_type)
예제 #34
0
파일: registry.py 프로젝트: zeninpalm/aiorm
def register(registred_type, *adapted_ifaces, adapt=IDriver):
    """ Register an adapter class for an original interface that implement
    adapted_ifaces. """
    assert registred_type, 'You need to pass an Interface'

    # deal with class->interface adapters:
    if not isinstance(adapt, interface.InterfaceClass):
        adapt = declarations.implementedBy(adapt)

    if not adapted_ifaces:
        adapted_ifaces = implementedBy(registred_type)

    for iface in adapted_ifaces:
        factory = _iface_registry.registered([adapt], iface)
        if factory is not None:
            raise ValueError('An adapter ({}) was already registered.'
                             'for iface {}'.format(factory, iface))

    for iface in adapted_ifaces:
        _iface_registry.register([adapt], iface, '', registred_type)
예제 #35
0
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.

    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
    __init__ method should accept one parameter, an instance implementing
    'origInterface'.
    """
    assert interfaceClasses, "You need to pass an Interface"

    # deal with class->interface adapters:
    if not isinstance(origInterface, interface.InterfaceClass):
        origInterface = declarations.implementedBy(origInterface)

    for interfaceClass in interfaceClasses:
        factory = _registered(_vcoRegistry, origInterface, interfaceClass)
        if factory is not None:
            raise ValueError("an adapter (%s) was already registered." % (factory, ))
    for interfaceClass in interfaceClasses:
        _vcoRegistry.register([origInterface], interfaceClass, '', adapterFactory)
예제 #36
0
def resolve(path):
    """Resolve a path.
    """
    if not path:
        return None

    if path.startswith('implementedBy: '):
        foo, path = path.split('implementedBy: ')
        implementer = zope_resolve(path)
        return implementedBy(implementer)

    try:
        return zope_resolve(path)

    except ImportError:
        if path.startswith('zope.interface.declarations.'):
            path = path[len('zope.interface.declarations.'):]
            return zope_resolve(path)

        else:
            raise
예제 #37
0
파일: registry.py 프로젝트: mardiros/apium
def register(registred_type, *adapted_ifaces, **kwargs):
    """ Register an adapter class for an original interface that implement
    adapted_ifaces. """
    assert registred_type, 'You need to pass an Interface'
    original_iface = kwargs.get('adapt', IDriver)

    # deal with class->interface adapters:
    if not isinstance(original_iface, interface.InterfaceClass):
        original_iface = declarations.implementedBy(original_iface)

    if not adapted_ifaces:
        adapted_ifaces = implementedBy(registred_type)

    for iface in adapted_ifaces:
        factory = _iface_registry.registered([original_iface], iface)
        if factory is not None:
            raise ValueError('an adapter (%s) was already registered.' %
                             (factory, ))

    for iface in adapted_ifaces:
        _iface_registry.register([original_iface], iface, '', registred_type)
예제 #38
0
def register(registred_type, *adapted_ifaces, **kwargs):
    """ Register an adapter class for an original interface that implement
    adapted_ifaces. """
    assert registred_type, 'You need to pass an Interface'
    original_iface = kwargs.get('adapt', ICaliop)

    # deal with class->interface adapters:
    if not isinstance(original_iface, interface.InterfaceClass):
        original_iface = declarations.implementedBy(original_iface)

    if not adapted_ifaces:
        adapted_ifaces = implementedBy(registred_type)

    for iface in adapted_ifaces:
        factory = _iface_registry.registered([original_iface], iface)
        if factory is not None:
            raise ValueError('an adapter (%s) was already registered.' %
                             (factory, ))

    for iface in adapted_ifaces:
        _iface_registry.register([original_iface], iface, '', registred_type)
예제 #39
0
    def __get__(self, inst, cls=None):

        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        # Find the cached value.
        cache = getattr(inst, '_v__providedBy__', None)

        # Find the data we need to know if our cache needs to be invalidated
        provided = alias_provides = getattr(inst, '__provides__', None)

        # See if we have a valid cache, and if so return it
        if cache is not None:
            cached_mtime, cached_provides, cached_provided = cache

            if (inst._p_mtime == cached_mtime
                    and alias_provides is cached_provides):
                return cached_provided

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if provided is None:
            assert cls == Alias  # XXX: remove
            provided = implementedBy(cls)

        # Add the interfaces provided by the target
        target = aq_base(inst._target)
        if target is None:
            return provided  # don't cache yet!

        # Add the interfaces provided by the target, but take away
        # IHasAlias if set
        provided += providedBy(target) - IHasAlias - IIterateAware

        if ITranslatable:
            provided -= ITranslatable

        inst._v__providedBy__ = inst._p_mtime, alias_provides, provided
        return provided
예제 #40
0
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.

    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
    __init__ method should accept one parameter, an instance implementing
    'origInterface'.
    """
    assert interfaceClasses, "You need to pass an Interface"

    # deal with class->interface adapters:
    if not isinstance(origInterface, interface.InterfaceClass):
        origInterface = declarations.implementedBy(origInterface)

    for interfaceClass in interfaceClasses:
        factory = _registered(_vcoRegistry, origInterface, interfaceClass)
        if factory is not None:
            raise ValueError("an adapter (%s) was already registered." %
                             (factory, ))
    for interfaceClass in interfaceClasses:
        _vcoRegistry.register([origInterface], interfaceClass, '',
                              adapterFactory)
예제 #41
0
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.

    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
    __init__ method should accept one parameter, an instance implementing
    'origInterface'.
    """
    self = globalRegistry
    assert interfaceClasses, "You need to pass an Interface"
    global ALLOW_DUPLICATES

    # deal with class->interface adapters:
    if not isinstance(origInterface, interface.InterfaceClass):
        origInterface = declarations.implementedBy(origInterface)

    for interfaceClass in interfaceClasses:
        factory = self.registered([origInterface], interfaceClass)
        if factory is not None and not ALLOW_DUPLICATES:
            raise ValueError(f"an adapter ({factory}) was already registered.")
    for interfaceClass in interfaceClasses:
        self.register([origInterface], interfaceClass, "", adapterFactory)
예제 #42
0
def registerAdapter(adapterFactory, origInterface, *interfaceClasses):
    """Register an adapter class.

    An adapter class is expected to implement the given interface, by
    adapting instances implementing 'origInterface'. An adapter class's
    __init__ method should accept one parameter, an instance implementing
    'origInterface'.
    """
    self = globalRegistry
    assert interfaceClasses, "You need to pass an Interface"
    global ALLOW_DUPLICATES

    # deal with class->interface adapters:
    if not isinstance(origInterface, interface.InterfaceClass):
        # fix up __implements__ if it's old style
        fixClassImplements(origInterface)
        origInterface = declarations.implementedBy(origInterface)

    for interfaceClass in interfaceClasses:
        factory = self.get(origInterface).selfImplied.get(interfaceClass, {}).get('')
        if (factory and not ALLOW_DUPLICATES):
            raise ValueError("an adapter (%s) was already registered." % (factory, ))
    for interfaceClass in interfaceClasses:
        self.register([origInterface], interfaceClass, '', adapterFactory)
예제 #43
0
def backwardsCompatImplements(klass):
    """Make a class have __implements__, for backwards compatability.

    This allows you to use new zope.interface APIs for declaring
    implements on classes, while still allowing subclasses that
    expect the old API.

       class YourClass:
           zope.interface.implements(IFoo) # correct zope way

       backwardsCompatImplements(YourClass) # add __implements__
       ----

       # someone else still hasn't updated their code:
       
       class ThirdPartyClass(YourClass):
           __implements__ = IBar, YourClass.__implements__

    """
    for subclass in klass.__bases__:
        fixClassImplements(subclass)
    
    _fixedClasses[klass] = True # so fixClassImplements will skip it
    klass.__implements__ = _implementsTuple(declarations.implementedBy(klass))
예제 #44
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        direct_spec = getattr(inst, '__provides__', None)

        # avoid recursion - fall back on default
        if getattr(self, '__recursion__', False):
            return direct_spec

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # Find the data we need to know if our cache needs to be invalidated
        portal_type = getattr(inst, 'portal_type', None)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)

        # See if we have a current cache. Reasons to do this include:
        #
        #  - The FTI was modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        updated = (inst._p_mtime, SCHEMA_CACHE.modified(portal_type),
                   SCHEMA_CACHE.invalidations, hash(direct_spec))
        if cache is not None and cache[:-1] == updated:
            if cache[-1] is not None:
                return cache[-1]
            return spec

        main_schema = SCHEMA_CACHE.get(portal_type)
        if main_schema:
            dynamically_provided = [main_schema]
        else:
            dynamically_provided = []

        # block recursion
        self.__recursion__ = True
        try:
            assignable = IBehaviorAssignable(inst, None)
            if assignable is not None:
                for behavior_registration in assignable.enumerateBehaviors():
                    if behavior_registration.marker:
                        dynamically_provided.append(
                            behavior_registration.marker)
        finally:
            del self.__recursion__

        if not dynamically_provided:
            # rare case if no schema nor behaviors with markers are set
            inst._v__providedBy__ = updated + (None, )
            return spec

        dynamically_provided.append(spec)
        all_spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (all_spec, )

        return all_spec
예제 #45
0
 def __init__(self, index_field):
     self.index_field = index_field
     self.__implemented__ = Implements(implementedBy(DelegatingIndexer))
예제 #46
0
 def __get__(self, inst, cls=None):
     
     # We're looking at a class - fall back on default
     if inst is None:
         return getObjectSpecification(cls)
     
     # Find the cached value. This calculation is expensive and called
     # hundreds of times during each request, so we require a fast cache
     cache = getattr(inst, '_v__providedBy__', None)
     
     # Find the data we need to know if our cache needs to be invalidated
     
     direct_spec = getattr(inst, '__provides__', None)
     portal_type = getattr(inst, 'portal_type', None)
     
     fti_counter = -1
     if portal_type is not None:
         fti_counter = SCHEMA_CACHE.counter(portal_type)
     
     # See if we have a valid cache. Reasons to do this include:
     # 
     #  - We don't have a portal_type yet, so we can't have found the schema
     #  - The FTI was modified, and the schema cache invalidated globally.
     #    The fti_counter will have advanced.
     #  - The instance was modified and persisted since the cache was built.
     #  - The instance now has a different __provides__, which means that someone
     #    called directlyProvides/alsoProvides on it.
     
     if cache is not None and portal_type is not None:
         cached_mtime, cached_fti_counter, cached_direct_spec, cached_spec = cache
         
         if inst._p_mtime == cached_mtime and \
                 fti_counter == cached_fti_counter and \
                 direct_spec is cached_direct_spec:
             return cached_spec
     
     # We don't have a cache, so we need to build a new spec and maybe cache it
     
     spec = direct_spec
     
     # If the instance doesn't have a __provides__ attribute, get the
     # interfaces implied by the class as a starting point.
     if spec is None:
         spec = implementedBy(cls)
     
     # Add the schema from the FTI and behavior subtypes
     
     dynamically_provided = []
     
     if portal_type is not None:
         schema = SCHEMA_CACHE.get(portal_type)
         if schema is not None:
             dynamically_provided.append(schema)
         
         subtypes = SCHEMA_CACHE.subtypes(portal_type)
         if subtypes:
             dynamically_provided.extend(subtypes)
     
     # If we have any dynamically provided interface, prepend them to the spec
     # and cache. We can't cache until we have at least the schema, because
     # it's possible that we were called before traversal and so could not
     # find the schema yet.
     
     if dynamically_provided:
         dynamically_provided.append(spec)
         spec = Implements(*dynamically_provided)
         
         inst._v__providedBy__ = inst._p_mtime, SCHEMA_CACHE.counter(portal_type), direct_spec, spec
     
     return spec
        class_ = "start"
        if b.isFinished() and not b.getSteps():
            # the steps have been pruned, so there won't be any indication
            # of whether it succeeded or failed. Color the box red or green
            # to show its status
            color = b.getColor()
            class_ = base.build_get_class(b)
        return base.Box([text], color=color, class_="BuildStep " + class_)


# First unregister ICurrentBox registered by waterfall.py.
# We won't be able to unregister it without messing with ALLOW_DUPLICATES
# in twisted.python.components. Instead, work directly with adapter to
# remove the component:
origInterface = statusbuilder.BuildStatus
origInterface = declarations.implementedBy(origInterface)
registry = components.getRegistry()
registry.register([origInterface], base.IBox, '', None)
components.registerAdapter(BuildBox, statusbuilder.BuildStatus, base.IBox)


class ChromiumStepBox(waterfall.StepBox):
    """Apply _ShortRev to the revision numbers in 'update' status boxes."""
    def getBox(self, req):
        text = self.original.getText()
        if len(text) > 1 and (text[0] == 'update' or text[0] == 'updating'):
            text[1] = _ShortRev(text[1])
        return waterfall.StepBox.getBox(self, req)


origInterface = statusbuilder.BuildStepStatus
예제 #48
0
 def __init__(self, callable):
     self.callable = callable
     self.__implemented__ = Implements(implementedBy(DelegatingIndexer))
     update_wrapper(self, callable)
예제 #49
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)

        # Find the data we need to know if our cache needs to be invalidated

        direct_spec = getattr(inst, '__provides__', None)
        portal_type = getattr(inst, 'portal_type', None)

        fti_counter = -1
        if portal_type is not None:
            fti_counter = SCHEMA_CACHE.counter(portal_type)

        # See if we have a valid cache. Reasons to do this include:
        #
        #  - We don't have a portal_type yet, so we can't have found the schema
        #  - The FTI was modified, and the schema cache invalidated globally.
        #    The fti_counter will have advanced.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance now has a different __provides__, which means that someone
        #    called directlyProvides/alsoProvides on it.

        if cache is not None and portal_type is not None:
            cached_mtime, cached_fti_counter, cached_direct_spec, cached_spec = cache

            if inst._p_mtime == cached_mtime and \
                    fti_counter == cached_fti_counter and \
                    direct_spec is cached_direct_spec:
                return cached_spec

        # We don't have a cache, so we need to build a new spec and maybe cache it

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # Add the schema from the FTI and behavior subtypes

        dynamically_provided = []

        if portal_type is not None:
            schema = SCHEMA_CACHE.get(portal_type)
            if schema is not None:
                dynamically_provided.append(schema)

            subtypes = SCHEMA_CACHE.subtypes(portal_type)
            if subtypes:
                dynamically_provided.extend(subtypes)

        # If we have any dynamically provided interface, prepend them to the spec
        # and cache. We can't cache until we have at least the schema, because
        # it's possible that we were called before traversal and so could not
        # find the schema yet.

        if dynamically_provided:
            dynamically_provided.append(spec)
            spec = Implements(*dynamically_provided)

            inst._v__providedBy__ = inst._p_mtime, SCHEMA_CACHE.counter(
                portal_type), direct_spec, spec

        return spec
예제 #50
0
    color = "yellow"
    class_ = "start"
    if b.isFinished() and not b.getSteps():
      # the steps have been pruned, so there won't be any indication
      # of whether it succeeded or failed. Color the box red or green
      # to show its status
      color = b.getColor()
      class_ = base.build_get_class(b)
    return base.Box([text], color=color, class_="BuildStep " + class_)

# First unregister ICurrentBox registered by waterfall.py.
# We won't be able to unregister it without messing with ALLOW_DUPLICATES
# in twisted.python.components. Instead, work directly with adapter to
# remove the component:
origInterface = statusbuilder.BuildStatus
origInterface = declarations.implementedBy(origInterface)
registry = components.getRegistry()
registry.register([origInterface], base.IBox, '', None)
components.registerAdapter(BuildBox, statusbuilder.BuildStatus, base.IBox)

class HorizontalOneBoxPerBuilder(base.HtmlResource):
  """This shows a table with one cell per build. The color of the cell is
  the state of the most recently completed build. If there is a build in
  progress, the ETA is shown in table cell. The table cell links to the page
  for that builder. They are layed out, you guessed it, horizontally.

  builder=: show only builds for this builder. Multiple builder= arguments
            can be used to see builds from any builder in the set. If no
            builder= is given, shows them all.
  """
예제 #51
0
    def __get__(self, inst, cls=None):  # noqa
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        direct_spec = getattr(inst, '__provides__', None)

        # avoid recursion - fall back on default
        if getattr(self, '__recursion__', False):
            return direct_spec

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # Find the data we need to know if our cache needs to be invalidated
        portal_type = getattr(inst, 'portal_type', None)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)

        # See if we have a current cache. Reasons to do this include:
        #
        #  - The FTI was modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        updated = (
            inst._p_mtime,
            SCHEMA_CACHE.modified(portal_type),
            SCHEMA_CACHE.invalidations,
            hash(direct_spec)
        )
        if cache is not None and cache[:-1] == updated:
            if cache[-1] is not None:
                return cache[-1]
            return spec

        main_schema = SCHEMA_CACHE.get(portal_type)
        if main_schema:
            dynamically_provided = [main_schema]
        else:
            dynamically_provided = []

        # block recursion
        self.__recursion__ = True
        try:
            assignable = IBehaviorAssignable(inst, None)
            if assignable is not None:
                for behavior_registration in assignable.enumerateBehaviors():
                    if behavior_registration.marker:
                        dynamically_provided.append(
                            behavior_registration.marker
                        )
        finally:
            del self.__recursion__

        if not dynamically_provided:
            # rare case if no schema nor behaviors with markers are set
            inst._v__providedBy__ = updated + (None, )
            return spec

        dynamically_provided.append(spec)
        all_spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (all_spec, )

        return all_spec
예제 #52
0
파일: delegate.py 프로젝트: Vinsurya/Plone
 def __init__(self, callable):
     self.callable = callable
     self.__implemented__ = Implements(implementedBy(DelegatingIndexer))
     update_wrapper(self, callable)
예제 #53
0
 def implementedBy(self, cls):
     """Do instances of the given class implement the interface?"""
     spec = implementedBy(cls)
     return self in spec._implied