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
def test_w_iface_type_not_IInterface(self): from zope.interface import Interface from zope.interface.interface import InterfaceClass class IFoo(Interface): pass IBar = InterfaceClass('IBar') self.assertRaises(TypeError, self._callFUT, 'xxx', IFoo, IBar)
def get_specification(spec, force=False): """Get the specification of the given object. If the given object is already a specification acceptable to the component architecture, it is simply returned. This is true for classes and specification objects (which includes interfaces). In case of instances, an interface is generated on the fly and tagged onto the object. Then the interface is returned as the specification. """ # If the specification is an instance, then we do some magic. if (force or (spec is not None and not ISpecification.providedBy(spec) and not isinstance(spec, class_types))): # Step 1: Calculate an interface name iface_name = 'IGeneratedForObject_%i' % id(spec) # Step 2: Find out if we already have such an interface existing_interfaces = [ i for i in directlyProvidedBy(spec) if i.__name__ == iface_name ] # Step 3a: Return an existing interface if there is one if len(existing_interfaces) > 0: spec = existing_interfaces[0] # Step 3b: Create a new interface if not else: iface = InterfaceClass(iface_name) alsoProvides(spec, iface) spec = iface return spec
def translate(self, table, annotation, __module__, **kw): annotation = annotation or TableAnnotation(table.name) iname = kw.get('interface_name') or 'I%sTable' % table.name field_map = self.generateFields(table, annotation) # apply manually overridden fields/properties self.applyProperties(field_map, annotation) # apply global schema ordering schema_order = kw.get('schema_order', None) or annotation.schema_order if schema_order: self.applyOrdering(field_map, schema_order) # verify table columns #if annotation.listing_columns: # self.verifyNames( field_map, annotation.listing_columns ) # extract base interfaces if 'bases' in kw: bases = (ITableSchema, ) + kw.get('bases') else: bases = (ITableSchema, ) DerivedTableSchema = InterfaceClass(iname, attrs=field_map, bases=bases, __module__=__module__) self.applyTaggedValues(DerivedTableSchema, annotation, kw) return DerivedTableSchema
def translate( self, table, annotation, __module__, **kw): annotation = annotation or {} visitor = ColumnVisitor(annotation) iname ='I%sTable'%table.name d = {} order_max = 0 for column in table.columns: if annotation.get( column.name, {}).get('omit', False ): continue d[ column.name ] = visitor.visit( column ) order_max = max( order_max, d[ column.name ].order ) if 'properties' in kw: for name, field in kw['properties'].items(): # append new fields if name not in d: order_max = order_max + 1 field.order = order_max # replace in place old fields else: field.order = d[name].order d[ name ] = field DerivedTableSchema = InterfaceClass( iname, (ITableSchema,), attrs=d, __module__ = __module__ ) # pprint.pprint(schema.getFieldsInOrder( DerivedTableSchema )) return DerivedTableSchema
def register_settings(name, *fields, **kw): """ register settings group """ iname = name for ch in ('.', '-'): iname = iname.replace(ch, '_') category = InterfaceClass('SettingsGroup:%s' % iname.upper(), (), __doc__='Settings group: %s' % name, __module__='ptah.config.settings') for field in fields: field.required = False if field.default is form.null: raise StopException( 'Default value is required for "{0}.{1}"'.format( name, field.name)) group = Group(name=name, *fields, **kw) interface.directlyProvides(Group, category) info = config.DirectiveInfo() discr = (ID_SETTINGS_GROUP, name) intr = config.Introspectable(ID_SETTINGS_GROUP, discr, group.__title__, ID_SETTINGS_GROUP) intr['name'] = name intr['group'] = group intr['codeinfo'] = info.codeinfo info.attach( config.Action( lambda config, group: config.get_cfg_storage(ID_SETTINGS_GROUP)\ .update({group.__name__: group.clone(config.registry)}), (group,), discriminator=discr, introspectables=(intr,)) )
def _register(components, procurement_method_type): iface = InterfaceClass("I{}Auction".format(procurement_method_type), bases=(Interface, )) components.add_auction(iface, procurementMethodType=procurement_method_type) components.registerAdapter(Planning, (IAuctionDatabridge, IFeedItem), iface) components.registerAdapter(RunDispatcher, (IAuctionsChronograph, IFeedItem), iface)
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)
def make_deep_inheritance(): children = [] base = Interface for iface in ifaces: child = InterfaceClass('IDerived' + base.__name__, ( iface, base, ), {}) base = child children.append(child) return children
def __call__(self, name, module): """Someone tried to load a dynamic interface that has not yet been created yet. We will attempt to load it from the FTI if we can. If the FTI doesn't exist, create a temporary marker interface that we can fill later. The goal here is to ensure that we create exactly one interface instance for each name. If we can't find an FTI, we'll cache the interface so that we don't get a new one with a different id later. This cache is global, so we synchronise the method with a thread lock. Once we have a properly populated interface, we set it onto the module using setattr(). This means that the factory will not be invoked again. """ try: prefix, portal_type, schemaName = splitSchemaName(name) except ValueError: return None if name in self._transient_SCHEMA_CACHE: schema = self._transient_SCHEMA_CACHE[name] else: bases = () is_default_schema = not schemaName if is_default_schema: bases += (IDexteritySchema,) schema = InterfaceClass(name, bases, __module__=module.__name__) if is_default_schema: alsoProvides(schema, IContentType) if portal_type is not None: fti = queryUtility(IDexterityFTI, name=portal_type) else: fti = None if fti is None and name not in self._transient_SCHEMA_CACHE: self._transient_SCHEMA_CACHE[name] = schema elif fti is not None: model = fti.lookupModel() syncSchema(model.schemata[schemaName], schema, sync_bases=True) # Save this schema in the module - this factory will not be # called again for this name if name in self._transient_SCHEMA_CACHE: del self._transient_SCHEMA_CACHE[name] setattr(module, name, schema) return schema
def create_behaviors_factory(proto_name, proto_definition): if proto_definition.get("for", None) is None: raise Exception("We need a for interface") else: for_ = import_class(proto_definition.get("for")) if for_ is None: raise Exception("Wrong for interface") parent_class = import_class( proto_definition.get( "inherited_class", "guillotina.behaviors.instance.AnnotationBehavior")) schema_fields, tags = get_fields( properties=proto_definition.get("properties")) base_interface = proto_definition.get("base_interface", None) if base_interface is None: base_interface = Interface class_interface = InterfaceClass( "I" + proto_name, (base_interface, ), schema_fields, __module__="guillotina.contrib.dyncontent.interfaces", ) for field_id, tag in tags.items(): for tag_id, tag_metadata in tag.items(): if tag_id in SUPPORTED_DIRECTIVES: SUPPORTED_DIRECTIVES[tag_id].apply(class_interface, field_id, tag_metadata) klass = type(proto_name, (parent_class, ), {}) klass.__module__ = "guillotina.contrib.dyncontent.behaviors" setattr(behaviors, proto_name, klass) behavior = { "for_": for_, "provides": class_interface, "data_key": proto_definition.get("data_key", "default"), "auto_serialize": proto_definition.get("auto_serialize", True), "name": proto_name, "name_only": proto_definition.get("name_only", False), "title": proto_definition.get("title", ""), "marker": proto_definition.get("marker", None), "description": proto_definition.get("description", ""), } configure.register_configuration(klass, behavior, "behavior")
def _makeDerivedSchema(base=None): from guillotina.schema import Bytes if base is None: base = _makeSchema() return InterfaceClass( "ISchemaTestSubclass", (base,), {"foo": Bytes(title="Foo", description="Fooness", default=b"", required=False)}, "", "guillotina.schema.tests.test_schema", )
def _makeDerivedSchema(base=None): from guillotina.schema import Bytes if base is None: base = _makeSchema() return InterfaceClass( 'ISchemaTestSubclass', (base, ), { 'foo': Bytes(title='Foo', description='Fooness', default=b"", required=False) }, '', 'guillotina.schema.tests.test_schema')
def flatten_interfaces(args): result = [] for a in args: if isinstance(a, (list, tuple)): result.extend(flatten_interfaces(a)) elif IInterface.providedBy(a): result.append(a) else: log.warning(' replacing %s with a placeholder', repr(a)) result.append( InterfaceClass(a.__name__, __module__='broken ' + a.__module__)) return result
def _makeSchema(): from zope.interface import Interface from guillotina.schema import Bytes return InterfaceClass( "ISchemaTest", (Interface,), { "title": Bytes(title="Title", description="Title", default=b"", required=True), "description": Bytes(title="Description", description="Description", default=b"", required=True), "spam": Bytes(title="Spam", description="Spam", default=b"", required=True), }, "", "guillotina.schema.tests.test_schema", )
def update(self): current_state = api.content.get_state(obj=self.context) states = self._states[:self._states.index(current_state) + 1] for idx, state in enumerate(states): self.fields += Fields( InterfaceClass( "IWorkflowHistory{0}", attrs={ state: schema.Date(title=translate(state, domain="plone"), required=True) for l in self.workflow if l.get("review_state") == state }, )) super(WorkflowHistoryForm, self).update()
def schema(self): """Generated schema based on csv file columns""" first_line = [] data_lines = [] data = self._get_data() encoding = "utf-8" has_header = data["has_header"] with data["source"].open() as f: f.seek(0) reader = csv.reader(f, delimiter=data["separator"].encode(encoding)) first_line = reader.next() try: for i in range(0, 2): data_lines.append(reader.next()) except Exception: pass fields = [] for idx, element in enumerate(first_line): if has_header: name = element.decode(encoding) else: name = str(idx + 1) sample = u", ".join([ u"'{0}'".format(ln[idx].decode(encoding)) for ln in data_lines ]) fields.append( GeneratedChoice( title=_("Column ${name}", mapping={"name": name}), description=_("Sample data : ${data}", mapping={"data": sample}), vocabulary=self._vocabulary, required=False, )) return InterfaceClass( "IImportSecondStep", attrs={ "column_{0}".format(idx): field for idx, field in enumerate(fields) }, bases=(self.base_schema, ), )
def _makeSchema(): from zope.interface import Interface from guillotina.schema import Bytes return InterfaceClass( 'ISchemaTest', (Interface, ), { 'title': Bytes( title="Title", description="Title", default=b"", required=True), 'description': Bytes(title="Description", description="Description", default=b"", required=True), 'spam': Bytes(title="Spam", description="Spam", default=b"", required=True) }, '', 'guillotina.schema.tests.test_schema')
def _iface_for_type(obj): # if the object is an interface then we can quit early if IInterface.providedBy(obj): return obj # look for a cached iface iface = obj.__dict__.get('_service_iface', None) if iface is not None: return iface # make a new iface and cache it on the object name = obj.__qualname__ iface = InterfaceClass( '%s_%s_IService' % (name, id(obj)), __doc__='service_factory generated interface', ) obj._service_iface = iface return iface
def schema_from_model(model): table = model.__table__ bases = (Interface, ) attrs = {} for i, column in enumerate(table.columns): if len(column.foreign_keys) or column.primary_key: continue field = IField(column.type) field.__name__ = str(column.name) field.title = unicode(column.name) field.required = not column.nullable attrs[column.name] = field field.order = i return InterfaceClass(name=model.__table__.name, bases=bases, attrs=attrs, __doc__='Generated from metadata')
def viewletManagerDirective(_context, id): id = str(id) # ensure native string if id in dir(viewlets): # pragma: no cover # The name functions as the identity, so this is # idempotent. return # We must do our work right now so that it can # be used by other directives. manager = InterfaceClass( id, (IViewletManager,), __doc__='Viewlet Manager', __module__='nti.nikola_chameleon.viewlets' ) manager.setTaggedValue("zcml_created", True) setattr(viewlets, id, manager)
def installSiteHook(_context, class_, site_class=None, utility_service=None): if site_class is None: if not IPossibleSite.implementedBy(class_): # This is not a possible site, we need to monkey-patch it so that # it is. site_class = FiveSite else: if not IPossibleSite.implementedBy(site_class): raise ConfigurationError('Site class does not implement ' 'IPossibleClass: %s' % site_class) if site_class is not None: _context.action( discriminator = (class_,), callable = classSiteHook, args=(class_, site_class) ) _context.action( discriminator = (class_, ISite), callable = classImplements, args=(class_, ISite) ) if utility_service is None: utility_service = SimpleLocalUtilityService else: if not ILocalUtilityService.implementedBy(utility_service): raise ConfigurationError('utility_service does not implement ' 'ILocalUtilityService: %s' % utility_service) # Generate a marker interface that should be unique, so that # we can register the utility service only for this class. iface = InterfaceClass('IFiveSite%s' % next()) adapter(_context, factory=(utility_service,), provides=ILocalUtilityService, for_=(iface,)) _context.action( discriminator = (class_, 'UtilityMarker'), callable = classImplements, args=(class_, iface) ) _localsite_monkies.append(class_)
def __call__(self, name, module): if name.startswith('__'): return None global loaded # use schema-saver to get interface signature = name[1:] # "I[md5hex]" -> "[md5hex]" if signature in loaded: return loaded[signature] saver = queryUtility(ISchemaSaver) if signature in saver: schema = saver.load(saver.get(signature)) # schema/iface object loaded[signature] = schema else: # otherwise load a placeholder interface logger.warning('SignatureSchemaFactory: ' 'Unable to obtain dynamic schema from ' 'serialization; using placeholder.') schema = InterfaceClass( name, (Interface), __module__=module.__name__, ) # placeholder (anonymous marker) interface return schema
def create_content_factory(proto_name, proto_definition): parent_interface = import_class( proto_definition.get("inherited_interface", "guillotina.interfaces.content.IFolder")) parent_class = import_class( proto_definition.get("inherited_class", "guillotina.content.Folder")) schema_fields, tags = get_fields( properties=proto_definition.get("properties")) class_interface = InterfaceClass( "I" + proto_name, (parent_interface, ), schema_fields, __module__="guillotina.contrib.dyncontent.interfaces", ) for field_id, tag in tags.items(): for tag_id, tag_metadata in tag.items(): if tag_id in SUPPORTED_DIRECTIVES: if tag_metadata is None: SUPPORTED_DIRECTIVES[tag_id].apply(class_interface, field_id) elif isinstance(tag_metadata, dict): SUPPORTED_DIRECTIVES[tag_id].apply(class_interface, field_id, **tag_metadata) elif isinstance(tag_metadata, list): SUPPORTED_DIRECTIVES[tag_id].apply(class_interface, field_id, *tag_metadata) elif tag_id == "fieldset": SUPPORTED_DIRECTIVES[tag_id].apply(class_interface, field_id, tag_metadata) elif isinstance(tag_metadata, str): SUPPORTED_DIRECTIVES[tag_id].apply( class_interface, **{field_id: tag_metadata}) klass = type(proto_name, (parent_class, ), {}) klass.__module__ = "guillotina.contrib.dyncontent.contents" setattr(contents, proto_name, klass) behaviors = [] for bhr in proto_definition.get("behaviors", []): if bhr in BEHAVIOR_CACHE: behaviors.append(BEHAVIOR_CACHE[bhr]) else: raise Exception(f"Behavior not found {bhr}") contenttype = { "schema": class_interface, "type_name": proto_name, "allowed_types": proto_definition.get("allowed_types", []), "add_permission": proto_definition.get("add_permission", "guillotina.AddContent"), "behaviors": behaviors, } utility = query_utility(IResourceFactory, name=proto_name) if utility is not None: sm = get_global_components() sm.unregisterUtility(utility, IResourceFactory, proto_name) configure.register_configuration(klass, contenttype, "contenttype")
def onDiscovery(self, theme, settings, dependenciesSettings): layer = InterfaceClass(theme, (Interface,), __module__=schemata.__name__) setattr(schemata, theme, layer)
class IMyInterface(Interface): __module__ = 'zodbbrowser.nosuchmodule' class IMyGoodInterface(Interface): pass class NotAnInterface(object): """A stand in for a ZODB Broken object""" __module__ = 'zodbbrowser.nosuchmodule' __name__ = 'NotAnInterface' FixedNotAnInterface = InterfaceClass( 'NotAnInterface', __module__='broken zodbbrowser.nosuchmodule') class CrashOnUnpickling(object): def __getstate__(self): return {} def __setstate__(self, state): raise Exception('oops') class TestFlattenInterfaces(unittest.TestCase): def test(self): self.assertEqual( flatten_interfaces([ IMyGoodInterface, NotAnInterface,
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
for attacher in actionAttachers: attacher.attachActionBindings(possibleActions) methods.sort(_sorter) properties.sort(_sorter) cls.__spec__ = spec = methods + properties spec.sort(_sorter) cls.name = name # because attributes "label" and "description" would become Properties, # check for ones with an underscore prefix. cls.label = dct.get('_label', None) cls.description = dct.get('_description', None) defaultLabel, defaultDescription = labelAndDescriptionFromDocstring( dct.get('__doc__')) if defaultLabel is None: defaultLabel = nameToLabel(name) if cls.label is None: cls.label = defaultLabel if cls.description is None: cls.description = defaultDescription return rv ####################################### ## External API; subclass this to create a TypedInterface ####################################### TypedInterface = MetaTypedInterface('TypedInterface', (InterfaceClass('TypedInterface'), ), {})
import pyperf from zope.interface import Interface from zope.interface import classImplements from zope.interface import implementedBy from zope.interface.interface import InterfaceClass from zope.interface.registry import Components # Long, mostly similar names are a worst case for equality # comparisons. ifaces = [ InterfaceClass('I' + ('0' * 20) + str(i), (Interface, ), {}) for i in range(100) ] class IWideInheritance(*ifaces): """ Inherits from 100 unrelated interfaces. """ class WideInheritance(object): pass classImplements(WideInheritance, IWideInheritance) def make_deep_inheritance(): children = []
def create(self, cls): name = "I{}".format(cls.__name__) return InterfaceClass(name)