本文整理汇总了Python中zope.interface.interface.InterfaceClass类的典型用法代码示例。如果您正苦于以下问题:Python InterfaceClass类的具体用法?Python InterfaceClass怎么用?Python InterfaceClass使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InterfaceClass类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: menuDirective
def menuDirective(_context, id=None, class_=BrowserMenu, interface=None,
title=u'', description=u''):
"""Registers a new browser menu."""
if id is None and interface is None:
raise ConfigurationError(
"You must specify the 'id' or 'interface' attribute.")
if interface is None:
if id in dir(menus):
# reuse existing interfaces for the id, without this we are not
# able to override menus.
interface = getattr(menus, id)
else:
interface = InterfaceClass(id, (),
__doc__='Menu Item Type: %s' %id,
__module__='zope.app.menus')
# Add the menu item type to the `menus` module.
# Note: We have to do this immediately, so that directives using the
# MenuField can find the menu item type.
setattr(menus, id, interface)
path = 'zope.app.menus.' + id
else:
path = interface.__module__ + '.' + interface.getName()
# If an id was specified, make this menu available under this id.
# Note that the menu will be still available under its path, since it
# is an adapter, and the `MenuField` can resolve paths as well.
if id is None:
id = path
else:
# Make the interface available in the `zope.app.menus` module, so
# that other directives can find the interface under the name
# before the CA is setup.
_context.action(
discriminator=('browser', 'MenuItemType', path),
callable=provideInterface,
args=(path, interface, IMenuItemType, _context.info)
)
setattr(menus, id, interface)
# Register the layer interface as an interface
_context.action(
discriminator=('interface', path),
callable=provideInterface,
args=(path, interface),
kw={'info': _context.info}
)
# Register the menu item type interface as an IMenuItemType
_context.action(
discriminator=('browser', 'MenuItemType', id),
callable=provideInterface,
args=(id, interface, IMenuItemType, _context.info)
)
# Register the menu as a utility
utility(_context, IBrowserMenu, class_(id, title, description), name=id)
开发者ID:zopefoundation,项目名称:zope.browsermenu,代码行数:57,代码来源:metaconfigure.py
示例2: test__uncached_lookupAll_empty_ro
def test__uncached_lookupAll_empty_ro(self):
from zope.interface.interface import InterfaceClass
IFoo = InterfaceClass('IFoo')
IBar = InterfaceClass('IBar', IFoo)
registry = self._makeRegistry()
alb = self._makeOne(registry)
result = alb._uncached_lookupAll((IFoo,), IBar)
self.assertEqual(result, ())
self.assertEqual(len(alb._required), 1)
self.failUnless(IFoo.weakref() in alb._required)
开发者ID:0004c,项目名称:VTK,代码行数:10,代码来源:test_adapter.py
示例3: __init__
def __init__(self, *arg, **kw):
try:
attrs = arg[2] or {}
except IndexError:
attrs = kw.get("attrs", {})
si = attrs.pop("source_integrity", False)
ti = attrs.pop("target_integrity", False)
InterfaceClass.__init__(self, *arg, **kw)
self.setTaggedValue("source_integrity", si)
self.setTaggedValue("target_integrity", ti)
开发者ID:geohuz,项目名称:substanced,代码行数:10,代码来源:interfaces.py
示例4: __init__
def __init__(self, *arg, **kw):
try:
attrs = arg[2] or {}
except IndexError:
attrs = kw.get('attrs', {})
si = attrs.pop('source_integrity', False)
ti = attrs.pop('target_integrity', False)
so = attrs.pop('source_ordered', False)
to = attrs.pop('target_ordered', False)
InterfaceClass.__init__(self, *arg, **kw)
self.setTaggedValue('source_integrity', si)
self.setTaggedValue('target_integrity', ti)
self.setTaggedValue('source_ordered', so)
self.setTaggedValue('target_ordered', to)
开发者ID:Adniel,项目名称:substanced,代码行数:14,代码来源:interfaces.py
示例5: route_request_iface
def route_request_iface(name, bases=()):
# zope.interface treats the __name__ as the __doc__ and changes __name__
# to None for interfaces that contain spaces if you do not pass a
# nonempty __doc__ (insane); see
# zope.interface.interface.Element.__init__ and
# https://github.com/Pylons/pyramid/issues/232; as a result, always pass
# __doc__ to the InterfaceClass constructor.
iface = InterfaceClass('%s_IRequest' % name, bases=bases,
__doc__="route_request_iface-generated interface")
# for exception view lookups
iface.combined = InterfaceClass(
'%s_combined_IRequest' % name,
bases=(iface, IRequest),
__doc__ = 'route_request_iface-generated combined interface')
return iface
开发者ID:DeanHodgkinson,项目名称:pyramid,代码行数:15,代码来源:request.py
示例6: wrapSchema
def wrapSchema(self, sch, field, hfields):
wschema = InterfaceClass(sch.__name__, (interface.Interface,),
__doc__ = sch.__doc__,
__module__ = 'memphisttw.schema.schemas')
for name, fld in schema.getFieldsInOrder(sch):
if name in self.skipFields or name in hfields:
continue
mfield = self.mapField(name, fld)
if mfield is not None:
fld = mfield(
__name__ = name,
title = fld.title,
description = fld.description,
required = False)
if fld.__class__ == schema.Field:
continue
wschema._InterfaceClass__attrs[name] = fld
return wschema
开发者ID:fafhrd91,项目名称:memphis-dev,代码行数:23,代码来源:factories.py
示例7: __init__
def __init__(self, *arg, **kw):
try:
attrs = arg[2] or {}
except IndexError:
attrs = kw.get('attrs', {})
# get class attribute values and remove them
si = attrs.pop('source_integrity', False)
ti = attrs.pop('target_integrity', False)
so = attrs.pop('source_ordered', False)
to = attrs.pop('target_ordered', False)
sif = attrs.pop('source_isheet', ISheet)
sifa = attrs.pop('source_isheet_field', u'')
tif = attrs.pop('target_isheet', ISheet)
# initialize interface class
InterfaceClass.__init__(self, *arg, **kw)
# set tagged values based on attribute values
self.setTaggedValue('source_integrity', si)
self.setTaggedValue('target_integrity', ti)
self.setTaggedValue('source_ordered', so)
self.setTaggedValue('target_ordered', to)
self.setTaggedValue('source_isheet', sif)
self.setTaggedValue('source_isheet_field', sifa)
self.setTaggedValue('target_isheet', tif)
开发者ID:pra85,项目名称:adhocracy3,代码行数:23,代码来源:interfaces.py
示例8: __call__
def __call__(self, other, default=_notag):
""" XXX use TypedInterfaceConfigurable as a fallback if this interface doesn't
work for some reason
"""
result = InterfaceClass.__call__(self, other, _notag)
if result is not _notag:
return result
from formless.annotate import TypedInterface
if TypedInterface.providedBy(other):
from formless.configurable import TypedInterfaceConfigurable
return TypedInterfaceConfigurable(other)
if default is _notag:
raise TypeError('Could not adapt', other, self)
return default
开发者ID:,项目名称:,代码行数:14,代码来源:
示例9: __init__
def __init__(self, *args, **kw):
Persistent.__init__(self)
InterfaceClass.__init__(self, *args, **kw)
self.dependents = PersistentDict()
开发者ID:wpjunior,项目名称:proled,代码行数:5,代码来源:__init__.py
示例10: __init__
def __init__(self, name, bases=(), attrs=None, __doc__=None,
__module__=None):
InterfaceClass.__init__(self, name, bases, attrs, __doc__, __module__)
self._SchemaClass_finalize()
开发者ID:seanupton,项目名称:plone.supermodel,代码行数:4,代码来源:model.py
示例11: route_request_iface
def route_request_iface(name, bases=()):
iface = InterfaceClass('%s_IRequest' % name, bases=bases)
# for exception view lookups
iface.combined = InterfaceClass('%s_combined_IRequest' % name,
bases=(iface, IRequest))
return iface
开发者ID:jkrebs,项目名称:pyramid,代码行数:6,代码来源:request.py
示例12: __init__
def __init__(self, name, bases=(), attrs=None, __doc__=None, __module__=None):
InterfaceClass.__init__(self, name, bases, attrs, __doc__, __module__)
开发者ID:AnthonyNystrom,项目名称:YoGoMee,代码行数:2,代码来源:entity.py
示例13: skin
def skin(_context, name=None, interface=None, layers=None):
"""Provides a new skin.
>>> import pprint
>>> class Context(object):
... info = u'doc'
... def __init__(self): self.actions = []
... def action(self, **kw): self.actions.append(kw)
>>> class Layer1(ILayer): pass
>>> class Layer2(ILayer): pass
Possibility 1: The Old Way
--------------------------
>>> context = Context()
>>> skin(context, u'skin1', layers=[Layer1, Layer2])
>>> iface = context.actions[3]['args'][1]
>>> iface.getName()
'skin1'
>>> pprint.pprint(iface.__bases__)
(<InterfaceClass zope.app.publisher.browser.metaconfigure.Layer1>,
<InterfaceClass zope.app.publisher.browser.metaconfigure.Layer2>)
>>> hasattr(sys.modules['zope.app.skins'], 'skin1')
True
>>> del sys.modules['zope.app.skins'].skin1
Possibility 2: Just specify an interface
----------------------------------------
>>> class skin1(Layer1, Layer2):
... pass
>>> context = Context()
>>> skin(context, interface=skin1)
>>> context.actions[0]['args'][1] is skin1
True
Possibility 3: Specify an interface and a Name
----------------------------------------------
>>> context = Context()
>>> skin(context, name='skin1', interface=skin1)
>>> context.actions[0]['args'][1] is skin1
True
>>> import pprint
>>> pprint.pprint([action['discriminator'] for action in context.actions])
[('skin', 'skin1'),
('interface', 'zope.app.publisher.browser.metaconfigure.skin1'),
('skin', 'zope.app.publisher.browser.metaconfigure.skin1')]
Here are some disallowed configurations.
>>> context = Context()
>>> skin(context)
Traceback (most recent call last):
...
ConfigurationError: You must specify the 'name' or 'interface' attribute.
>>> skin(context, layers=[Layer1])
Traceback (most recent call last):
...
ConfigurationError: You must specify the 'name' or 'interface' attribute.
"""
if name is None and interface is None:
raise ConfigurationError("You must specify the 'name' or 'interface' attribute.")
if name is not None and layers is not None:
interface = InterfaceClass(str(name), layers, __doc__="Skin: %s" % str(name), __module__="zope.app.skins")
# Add the layer to the skins module.
# Note: We have to do this immediately, so that directives using the
# InterfaceField can find the layer.
setattr(zope.app.skins, name, interface)
path = "zope.app.skins" + name
# Register the layers
for layer in layers:
_context.action(
discriminator=None, callable=provideInterface, args=(layer.getName(), layer, ILayer, _context.info)
)
else:
path = interface.__module__ + "." + interface.getName()
# Register the skin interface as a skin using the passed name.
if name is not None:
_context.action(
discriminator=("skin", name), callable=provideInterface, args=(name, interface, ISkin, _context.info)
)
name = path
# Register the skin interface as an interface
_context.action(
discriminator=("interface", path), callable=provideInterface, args=(path, interface), kw={"info": _context.info}
)
# Register the skin interface as a skin
_context.action(
#.........这里部分代码省略.........
开发者ID:wpjunior,项目名称:proled,代码行数:101,代码来源:metaconfigure.py
示例14: __init__
def __init__(self, name):
InterfaceClass.__init__(self, name, (Interface,))
Baz.__init__(self, name)
开发者ID:,项目名称:,代码行数:3,代码来源:
示例15: __new__
def __new__(cls, name, bases, dct):
rv = cls = InterfaceClass.__new__(cls)
cls.__id__ = nextId()
cls.__methods__ = methods = []
cls.__properties__ = properties = []
cls.default = 'DEFAULT'
cls.complexType = True
possibleActions = []
actionAttachers = []
for key, value in list(dct.items()):
if key[0] == '_': continue
if isinstance(value, MetaTypedInterface):
## A Nested TypedInterface indicates a GroupBinding
properties.append(GroupBinding(key, value, value.__id__))
## zope.interface doesn't like these
del dct[key]
setattr(cls, key, value)
elif isinstance(value, collections.Callable):
names, _, _, typeList = inspect.getargspec(value)
_testCallArgs = ()
if typeList is None:
typeList = []
if len(names) == len(typeList) + 1:
warnings.warn(
"TypeInterface method declarations should not have a 'self' parameter",
DeprecationWarning,
stacklevel=2)
del names[0]
_testCallArgs = (_Marker,)
if len(names) != len(typeList):
## Allow non-autocallable methods in the interface; ignore them
continue
argumentTypes = [
Argument(n, argtype, argtype.id) for n, argtype in zip(names[-len(typeList):], typeList)
]
result = value(*_testCallArgs)
label = None
description = None
if getattr(value, 'autocallable', None):
# autocallables have attributes that can set label and description
label = value.attributes.get('label', None)
description = value.attributes.get('description', None)
adapted = iformless.ITyped(result, None)
if adapted is None:
adapted = Object(result)
# ITyped has label and description we can use
if label is None:
label = adapted.label
if description is None:
description = adapted.description
defaultLabel, defaultDescription = labelAndDescriptionFromDocstring(value.__doc__)
if defaultLabel is None:
# docstring had no label, try the action if it is an autocallable
if getattr(value, 'autocallable', None):
if label is None and value.action is not None:
# no explicit label, but autocallable has action we can use
defaultLabel = value.action
if defaultLabel is None:
# final fallback: use the function name as label
defaultLabel = nameToLabel(key)
if label is None:
label = defaultLabel
if description is None:
description = defaultDescription
theMethod = Method(
adapted, argumentTypes, label=label, description=description
)
if getattr(value, 'autocallable', None):
methods.append(
MethodBinding(
key, theMethod, value.id, value.action, value.attributes))
else:
possibleActions.append((value, MethodBinding(key, theMethod)))
else:
if not value.label:
value.label = nameToLabel(key)
if iformless.IActionableType.providedBy(value):
actionAttachers.append(value)
properties.append(
Property(key, value, value.id)
)
for attacher in actionAttachers:
attacher.attachActionBindings(possibleActions)
methods.sort(key=_sorter)
#.........这里部分代码省略.........
开发者ID:perkinslr,项目名称:nevow-py3,代码行数:101,代码来源:annotate.py
示例16: layer
def layer(_context, name=None, interface=None, base=IBrowserRequest):
"""Provides a new layer.
>>> class Context(object):
... info = u'doc'
... def __init__(self): self.actions = []
... def action(self, **kw): self.actions.append(kw)
Possibility 1: The Old Way
--------------------------
>>> context = Context()
>>> layer(context, u'layer1')
>>> iface = context.actions[0]['args'][1]
>>> iface.getName()
'layer1'
>>> ILayer.providedBy(iface)
True
>>> hasattr(sys.modules['zope.app.layers'], 'layer1')
True
>>> del sys.modules['zope.app.layers'].layer1
Possibility 2: Providing a custom base interface
------------------------------------------------
>>> class BaseLayer(IBrowserRequest):
... pass
>>> context = Context()
>>> layer(context, u'layer1', base=BaseLayer)
>>> iface = context.actions[0]['args'][1]
>>> iface.getName()
'layer1'
>>> iface.__bases__
(<InterfaceClass zope.app.publisher.browser.metaconfigure.BaseLayer>,)
>>> hasattr(sys.modules['zope.app.layers'], 'layer1')
True
>>> del sys.modules['zope.app.layers'].layer1
Possibility 3: Define a Layer just through an Interface
-------------------------------------------------------
>>> class layer1(IBrowserRequest):
... pass
>>> context = Context()
>>> layer(context, interface=layer1)
>>> context.actions[0]['args'][1] is layer1
True
>>> hasattr(sys.modules['zope.app.layers'], 'layer1')
False
Possibility 4: Use an Interface and a Name
------------------------------------------
>>> context = Context()
>>> layer(context, name='layer1', interface=layer1)
>>> context.actions[0]['args'][1] is layer1
True
>>> hasattr(sys.modules['zope.app.layers'], 'layer1')
True
>>> import pprint
>>> pprint.pprint([action['discriminator'] for action in context.actions])
[('interface', 'zope.app.publisher.browser.metaconfigure.layer1'),
('layer', 'layer1')]
Here are some disallowed configurations.
>>> context = Context()
>>> layer(context, 'foo,bar')
Traceback (most recent call last):
...
TypeError: Commas are not allowed in layer names.
>>> layer(context)
Traceback (most recent call last):
...
ConfigurationError: You must specify the 'name' or 'interface' attribute.
>>> layer(context, base=BaseLayer)
Traceback (most recent call last):
...
ConfigurationError: You must specify the 'name' or 'interface' attribute.
>>> layer(context, interface=layer1, base=BaseLayer)
Traceback (most recent call last):
...
ConfigurationError: You cannot specify the 'interface' and 'base' together.
"""
if name is not None and "," in name:
raise TypeError("Commas are not allowed in layer names.")
if name is None and interface is None:
raise ConfigurationError("You must specify the 'name' or 'interface' attribute.")
if interface and not interface.extends(IBrowserRequest):
raise ConfigurationError("The layer interface must extend `IBrowserRequest`.")
if base is not IBrowserRequest and not base.extends(IBrowserRequest):
raise ConfigurationError("The base interface must extend `IBrowserRequest`.")
if interface is not None and base is not IBrowserRequest:
raise ConfigurationError("You cannot specify the 'interface' and 'base' together.")
if interface is None:
interface = InterfaceClass(str(name), (base,), __doc__="Layer: %s" % str(name), __module__="zope.app.layers")
#.........这里部分代码省略.........
开发者ID:wpjunior,项目名称:proled,代码行数:101,代码来源:metaconfigure.py
示例17: __init__
def __init__(self, *args, **kw):
Persistent.__init__(self)
InterfaceClass.__init__(self, *args, **kw)
self.dependents = FlexibleWeakKeyDictionary()
开发者ID:grodniewicz,项目名称:oship,代码行数:5,代码来源:__init__.py
示例18: GenerateContainer
def GenerateContainer( ctx,
container_name=None,
container_iname=None,
base_interfaces=() ):
"""
generate a zope3 container class for a domain model
"""
# create container
container_name = container_name or \
ctx.domain_model.__name__ + 'Container'
# allow passing in dotted python path
if isinstance( ctx.container_module, (str, unicode) ):
ctx.container_module = resolve( ctx.container_module )
# if not present use the domain class's module
elif ctx.container_module is None:
ctx.container_module = resolve( ctx.domain_model.__module__ )
# sanity check we have a module for the container
assert isinstance(ctx.container_module, types.ModuleType ), "Invalid Container"
# logging variables
msg = ( ctx.domain_model.__name__,
ctx.container_module.__name__,
container_name )
# if we already have a container class, exit
if getattr( ctx.container_module, container_name, None ):
if ctx.echo:
ctx.logger.debug("%s: found container %s.%s, skipping"%msg )
ctx.container_class = getattr( ctx.container_module, container_name )
return
if ctx.echo:
ctx.logger.debug("%s: generated container %s.%s"%msg )
# if we already have a container class, exit
container_class = type( container_name,
(AlchemistContainer,),
dict(_class=ctx.domain_model,
__module__=ctx.container_module.__name__ )
)
setattr( ctx.container_module, container_name, container_class)
# save container class on catalyst context
ctx.container_class = container_class
# interface for container
container_iname = container_iname or "I%s"%container_name
# if the interface module is none, then use the nearest one to the domain class
if ctx.interface_module is None:
ispec = ctx.domain_model.__module__.rsplit('.',1)[0]+'.interfaces'
ctx.interface_module = resolve( ispec )
msg = ( ctx.domain_model.__name__,
ctx.container_module.__name__,
container_iname )
# if we already have a container interface class, skip creation
container_interface = getattr( ctx.interface_module, container_iname, None )
if container_interface is not None:
assert issubclass( container_interface, IAlchemistContainer )
if ctx.echo:
ctx.logger.debug("%s: skipping container interface %s.%s for"%msg )
else:
if ctx.echo:
ctx.logger.debug("%s: generated container interface %s.%s"%msg )
# ensure that our base interfaces include alchemist container
if base_interfaces:
assert isinstance( base_interfaces, tuple )
found = False
for bi in base_interfaces:
found = issubclass( bi, IAlchemistContainer )
if found: break
if not found:
base_interfaces = base_interfaces + ( IAlchemistContainer,)
else:
base_interfaces = ( IAlchemistContainer, )
# create interface
container_interface = InterfaceClass( container_iname,
bases = base_interfaces,
__module__ = ctx.interface_module.__name__
)
# store container interface for catalyst
ctx.container_interface = container_interface
setattr( ctx.interface_module, container_iname, container_interface )
# setup security
for n,d in container_interface.namesAndDescriptions(1):
protectName( container_class, n, "zope.Public")
if not container_interface.implementedBy(container_class):
interface.classImplements(container_class, container_interface)
#.........这里部分代码省略.........
开发者ID:kapilt,项目名称:zope-alchemist,代码行数:101,代码来源:container.py
示例19: parse
def parse(source, policy=u""):
tree = ElementTree.parse(source)
root = tree.getroot()
model = Model()
handlers = {}
schema_metadata_handlers = tuple(getUtilitiesFor(ISchemaMetadataHandler))
field_metadata_handlers = tuple(getUtilitiesFor(IFieldMetadataHandler))
policy_util = getUtility(ISchemaPolicy, name=policy)
def readField(fieldElement, schemaAttributes, fieldElements, baseFields):
# Parse field attributes
fieldName = fieldElement.get('name')
fieldType = fieldElement.get('type')
if fieldName is None or fieldType is None:
raise ValueError("The attributes 'name' and 'type' are required for each <field /> element")
handler = handlers.get(fieldType, None)
if handler is None:
handler = handlers[fieldType] = queryUtility(IFieldExportImportHandler, name=fieldType)
if handler is None:
raise ValueError("Field type %s specified for field %s is not supported" % (fieldType, fieldName, ))
field = handler.read(fieldElement)
# Preserve order from base interfaces if this field is an override
# of a field with the same name in a base interface
base_field = baseFields.get(fieldName, None)
if base_field is not None:
field.order = base_field.order
# Save for the schema
schemaAttributes[fieldName] = field
fieldElements[fieldName] = fieldElement
return fieldName
for schema_element in root.findall(ns('schema')):
schemaAttributes = {}
schema_metadata = {}
schemaName = schema_element.get('name')
if schemaName is None:
schemaName = u""
bases = ()
baseFields = {}
based_on = schema_element.get('based-on')
if based_on is not None:
bases = tuple([resolve(dotted) for dotted in based_on.split()])
for base_schema in bases:
baseFields.update(getFields(base_schema))
fieldElements = {}
# Read global fields
for fieldElement in schema_element.findall(ns('field')):
readField(fieldElement, schemaAttributes, fieldElements, baseFields)
# Read fieldsets and their fields
fieldsets = []
fieldsets_by_name = {}
for subelement in schema_element:
if subelement.tag == ns('field'):
readField(subelement, schemaAttributes, fieldElements, baseFields)
elif subelement.tag == ns('fieldset'):
fieldset_name = subelement.get('name')
if fieldset_name is None:
raise ValueError(u"Fieldset in schema %s has no name" % (schemaName))
fieldset = fieldsets_by_name.get(fieldset_name, None)
if fieldset is None:
fieldset_label = subelement.get('label')
fieldset_description = subelement.get('description')
fieldset = fieldsets_by_name[fieldset_name] = Fieldset(fieldset_name,
label=fieldset_label, description=fieldset_description)
fieldsets_by_name[fieldset_name] = fieldset
fieldsets.append(fieldset)
for fieldElement in subelement.findall(ns('field')):
parsed_fieldName = readField(fieldElement, schemaAttributes, fieldElements, baseFields)
if parsed_fieldName:
fieldset.fields.append(parsed_fieldName)
schema = InterfaceClass(name=policy_util.name(schemaName, tree),
bases=bases + policy_util.bases(schemaName, tree),
__module__=policy_util.module(schemaName, tree),
attrs=schemaAttributes)
schema.setTaggedValue(FIELDSETS_KEY, fieldsets)
# Save fieldsets
#.........这里部分代码省略.........
开发者ID:koodaamo,项目名称:plone.supermodel,代码行数:101,代码来源:parser.py
注:本文中的zope.interface.interface.InterfaceClass类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论