尝试注册 zope.interface 的实现者时出错

Error when try to register implementer of zope.interface

我有下一个class:

@implementer(ISocial)
class SocialVKSelenium:
    pass

当我将它添加到 zope 注册表时:

gsm = getGlobalSiteManager()
gsm.registerAdapter(SocialVKSelenium)

我得到了:TypeError: The adapter factory doesn't have a __component_adapts__ attribute and no required specifications were specified

当我添加适配器 (IOther) 时,注册按预期工作,但没有。为什么会这样?

您需要在 class 或注册表中提供上下文。

我怀疑你没有传达你的问题集的全部——适配器是一个组件,它适应一个指定的接口的对象,并提供另一个。您的示例未能指定正在调整的上下文是什么,也就是说,通过其 class?

在构建适配器对象时调整了哪种对象

例如,这很好用:

from zope.interface import Interface, implements
from zope.component import getGlobalSiteManager, adapts


class IWeight(Interface):
    pass


class IVolume(Interface):
    pass

class WeightToVolume(object):
    implements(IVolume)
    adapts(IWeight)
    #...


gsm = getGlobalSiteManager()
gsm.registerAdapter(WeightToVolume)

虽然您可以为此使用装饰器 (implementer/adapter) 语法,但按照惯例,对于 class 类型而非函数的适配器工厂,首选使用 implements/adapts。

如果您的适配器没有在 class 或工厂函数本身上声明它所适应的内容,您至少需要告知注册表。在最广泛的情况下,这可能看起来像:

gsm.registerAdapter(MyAdapterClassHere, required=(Interface,))

当然,上面这个例子是一个号称可以适配任何上下文的适配器,除非你知道为什么需要它,否则不推荐这样做。