def manage_FTPget(self, REQUEST=None, RESPONSE=None): """Return the body of the content item in an FTP or WebDAV response. This adapts self to IRawReadFile(), which is then returned as an iterator. The adapter should provide IStreamIterator. """ reader = IRawReadFile(self, None) if reader is None: return '' request = REQUEST is not None and REQUEST or self.REQUEST response = RESPONSE is not None and RESPONSE or request.response mimeType = reader.mimeType encoding = reader.encoding if mimeType is not None: if encoding is not None: response.setHeader('Content-Type', '%s; charset="%s"' % (mimeType, encoding,)) else: response.setHeader('Content-Type', mimeType) size = reader.size() if size is not None: response.setHeader('Content-Length', str(size)) # if the reader is an iterator that the publisher can handle, return # it as-is. Otherwise, read the full contents if ((IInterface.providedBy(IStreamIterator) and IStreamIterator.providedBy(reader)) or (not IInterface.providedBy(IStreamIterator) and IStreamIterator.isImplementedBy(reader)) ): return reader else: return reader.read()
def setup(self, catalog, name, context, module_info): # If the user supplied attribute= when instantiating us, we # allow that value to override the attribute name under which we # are actually stored inside of the `grokcore.catalog.Indexes` # instance. if self._attribute is not None: field_name = self._attribute else: field_name = name if IInterface.providedBy(context): try: method = context[field_name] except KeyError: raise GrokError( "grokcore.catalog.Indexes in %r refers to an attribute or " "method %r on interface %r, but this does not " "exist." % (module_info.getModule(), field_name, context), None) call = IMethod.providedBy(method) else: call = callable(getattr(context, field_name, None)) context = None # no interface lookup catalog[name] = self.index_class( field_name=field_name, interface=context, field_callable=call, *self._args, **self._kw)
def __init__(self, context, schema): if not IComposedQuery.providedBy(context): raise ValueError('context must provide IComposedQuery') if not IInterface.providedBy(schema): raise ValueError('schema provided must be interface') self.context = context self.schema = schema
def __init__(self, context, schema): if not IFilterGroup.providedBy(context): raise ValueError('context must provide IFilterGroup') if not IInterface.providedBy(schema): raise ValueError('schema provided must be interface') self.context = context self.schema = schema
def resolve_isheet_field_from_dotted_string(self, dotted: str) -> tuple: """Resolve `dotted` string to isheet and field name and schema node. :dotted: isheet.__identifier__ and field_name separated by ':' :return: tuple with isheet (ISheet), field_name (str), field schema node (colander.SchemaNode). :raise ValueError: If the string is not dotted or it cannot be resolved to isheet and field name. """ if ':' not in dotted: raise ValueError( 'Not a colon-separated dotted string: {}'.format(dotted)) name = ''.join(dotted.split(':')[:-1]) field = dotted.split(':')[-1] try: isheet = resolver.resolve(name) except ImportError: raise ValueError('No such sheet: {}'.format(name)) if not (IInterface.providedBy(isheet) and isheet.isOrExtends(ISheet)): raise ValueError('Not a sheet: {}'.format(name)) schema = self.sheets_meta[isheet].schema_class() node = schema.get(field, None) if not node: raise ValueError('No such field: {}'.format(dotted)) return isheet, field, node
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
def factory(self, schema): if not IInterface.providedBy(schema): raise GrokImportError( "You can only pass an interface to the " "provides argument of %s." % self.name) return schema
def find_parents(context, findone=False, start_depth=2, **kwargs): typename = kwargs.get("typename", None) iface = kwargs.get("iface", None) if IInterface.providedBy(iface): iface = iface.__identifier__ if findone and typename is None and iface is None: parent = getattr(context, "__parent__", None) if parent: return parent # immediate parent of context result = [] catalog = getToolByName(context, "portal_catalog") path = context.getPhysicalPath() subpaths = reversed([path[0:i] for i in range(len(path) + 1)][start_depth:]) for subpath in subpaths: query = {"path": {"query": "/".join(subpath), "depth": 0}} if typename is not None: query["portal_type"] = typename if iface is not None: query["object_provides"] = iface brains = catalog.unrestrictedSearchResults(query) if not brains: continue else: item = brains[0]._unrestrictedGetObject() if aq_base(item) is aq_base(context): continue # don't return or append the context itself! if findone: return item result.append(item) if findone: return None # never found one return result
def MultiChecker(specs): """Create a checker from a sequence of specifications A specification is: - A two-tuple with: o a sequence of names or an interface o a permission id All the names in the sequence of names or the interface are protected by the permission. - A dictionoid (having an items method), with items that are name/permission-id pairs. """ data = {} for spec in specs: if type(spec) is tuple: names, permission_id = spec if IInterface.providedBy(names): names = names.names(all=True) for name in names: if data.get(name, permission_id) is not permission_id: raise DuplicationError(name) data[name] = permission_id else: for name, permission_id in spec.items(): if data.get(name, permission_id) is not permission_id: raise DuplicationError(name) data[name] = permission_id return Checker(data)
def referential_integrity(event): if event.moving: return obj = event.object obj_oid = oid_of(obj, None) objectmap = find_objectmap(obj) if objectmap is None: return for reftype in objectmap.get_reftypes(): is_iface = IInterface.providedBy(reftype) if is_iface and reftype.queryTaggedValue('source_integrity', False): targetids = objectmap.targetids(obj, reftype) if obj_oid in targetids: targetids.remove(obj_oid) # self-referential if targetids: # object is a source raise SourceIntegrityError(obj, reftype, targetids) if is_iface and reftype.queryTaggedValue('target_integrity', False): sourceids = objectmap.sourceids(obj, reftype) if obj_oid in sourceids: sourceids.remove(obj_oid) # self-referential if sourceids: # object is a target raise TargetIntegrityError(obj, reftype, sourceids)
def available(self): # We are available if we have sublevel menu or a screen. return ( (len(self.submenu) != 0) or IUIScreen.implementedBy(self.screen) or (IInterface.providedBy(self.interface) and self.interface.extends(IUIScreen)) )
def provideInterface(id, interface, iface_type=None, info=''): """ Mark *interface* as a named utility providing *iface_type*'. .. versionchanged:: 5.0.0 The named utility is registered in the current site manager. Previously it was always registered in the global site manager. """ if not id: id = "%s.%s" % (interface.__module__, interface.__name__) if not IInterface.providedBy(interface): if not isinstance(interface, CLASS_TYPES): raise TypeError(id, "is not an interface or class") return if iface_type is not None: if not iface_type.extends(IInterface): raise TypeError(iface_type, "is not an interface type") alsoProvides(interface, iface_type) else: iface_type = IInterface site_man = getSiteManager() site_man.registerUtility(interface, iface_type, id, info)
def forget(self, schema): name = str(schema) if IInterface.providedBy(schema): name = identify_interface(schema) if name not in self._names: return self._names.remove(name)
def addMenuItem( menu_id, interface, action, title, description='', filter_string=None, permission=None, extra=None, ): registry = globalBrowserMenuService._registry[menu_id].registry if permission: if permission == 'zope.Public': permission = CheckerPublic if interface is not None and not IInterface.providedBy(interface): if isinstance(interface, (type, ClassType)): interface = implementedBy(interface) else: raise TypeError( "The interface argument must be an interface (or None) " "or a class.") data = registry.get(interface) or [] data.append( MenuItem(action, title, description, filter_string, permission, extra)) registry.register(interface, data)
def register(template=template): if isinstance(template, basestring): helper = renderers.RendererHelper(name=template, package=config.package, registry=config.registry) template = helper.renderer.implementation() layout_intr.update(dict(name=name, filename=template.filename, context=context, callable=layout)) introspectables.append(layout_intr) def derived_layout(context, request): wrapped = layout(context, request) wrapped.__layout__ = name wrapped.__template__ = template return wrapped r_context = context if r_context is None: r_context = Interface if not IInterface.providedBy(r_context): r_context = implementedBy(r_context) reg_layout = config.registry.adapters.lookup((r_context,), ILayout, name=name) if isinstance(reg_layout, _MultiLayout): reg_layout[containment] = derived_layout return elif containment: reg_layout = _MultiLayout(reg_layout) reg_layout[containment] = derived_layout else: reg_layout = derived_layout config.registry.registerAdapter(reg_layout, (context,), ILayout, name=name)
def identifier(obj): """Gives the Python identifier for the given object, so after we can do resolve on it to get it back. """ if IInterface.providedBy(obj): return obj.__identifier__ return obj.__name__
def resolve(name): """Resolve the name. """ obj = pythonResolve(name) if not IInterface.providedBy(obj): return obj.__provides__._implements return obj
def _validate(self, value): super(InterfaceField, self)._validate(value) if not IInterface.providedBy(value): raise NotAnInterface( value, self.__name__ ).with_field_and_value(self, value)
def __init__(self, required, provided=None, name=u''): if IInterface.providedBy(required): required = (required,) self.name = name self.required = required self.provided = provided
class FileStreamIterator(object): """Simple stream iterator to allow efficient data streaming. """ # Stupid workaround for the fact that on Zope < 2.12, we don't have # a real interface if IInterface.providedBy(IStreamIterator): implements(IStreamIterator) else: __implements__ = (IStreamIterator, ) def __init__(self, path, size=None, chunk=1 << 16): """Consume data (a str) into a temporary file and prepare streaming. size is the length of the data. If not given, the length of the data string is used. chunk is the chunk size for the iterator """ self.path = path self.file = open(path) self.file.seek(0) self.size = os.stat(path).st_size self.chunk = chunk def __iter__(self): return self def next(self): data = self.file.read(self.chunk) if not data: self.file.close() raise StopIteration return data def __len__(self): return self.size
def referential_integrity(event): if event.moving is not None: # being moved return objectmap = find_objectmap(event.object) if objectmap is None: return reftypes = list(objectmap.get_reftypes()) for oid in event.removed_oids: for reftype in reftypes: is_iface = IInterface.providedBy(reftype) if is_iface and reftype.queryTaggedValue('source_integrity', False): targetids = objectmap.targetids(oid, reftype) if oid in targetids: targetids.remove(oid) # self-referential if targetids: # object is a source obj = objectmap.object_for(oid) raise SourceIntegrityError(obj, reftype, targetids) if is_iface and reftype.queryTaggedValue('target_integrity', False): sourceids = objectmap.sourceids(oid, reftype) if oid in sourceids: sourceids.remove(oid) # self-referential if sourceids: # object is a target obj = objectmap.object_for(oid) raise TargetIntegrityError(obj, reftype, sourceids)
def __init__(self, schema=_NotGiven, **kw): """ Object(schema=<Not Given>, *, validate_invariants=True, **kwargs) Create an `~.IObject` field. The keyword arguments are as for `~.Field`. .. versionchanged:: 4.6.0 Add the keyword argument *validate_invariants*. When true (the default), the schema's ``validateInvariants`` method will be invoked to check the ``@invariant`` properties of the schema. .. versionchanged:: 4.6.0 The *schema* argument can be ommitted in a subclass that specifies a ``schema`` attribute. """ if schema is _NotGiven: schema = self.schema if not IInterface.providedBy(schema): # Note that we don't provide 'self' as the 'field' # by calling with_field_and_value(): We're not fully constructed, # we don't want this instance to escape. raise NotAnInterface(schema, self.__name__) self.schema = schema self.validate_invariants = kw.pop('validate_invariants', True) super(Object, self).__init__(**kw)
def get_registry_record(name=None, interface=None, default=MISSING): """Get a record value from ``plone.app.registry`` :param name: [required] Name :type name: string :param interface: interface whose attributes are plone.app.registry settings :type interface: zope.interface.Interface :param default: The value returned if the record is not found :type default: anything :returns: Registry record value :rtype: plone.app.registry registry record :Example: :ref:`portal_get_registry_record_example` """ if not isinstance(name, str): raise InvalidParameterError(u"The 'name' parameter has to be a string") if interface is not None and not IInterface.providedBy(interface): raise InvalidParameterError( u'The interface parameter has to derive from ' u'zope.interface.Interface', ) registry = getUtility(IRegistry) if interface is not None: records = registry.forInterface(interface) _marker = object() if getattr(records, name, _marker) != _marker: return registry['{0}.{1}'.format(interface.__identifier__, name)] if default is not MISSING: return default # Show all records on the interface. records = [key for key in interface.names()] msg = ('Cannot find a record with name "{name}"' ' on interface {identifier}.\n' 'Did you mean?\n' '{records}'.format( name=name, identifier=interface.__identifier__, records='\n'.join(records), )) raise InvalidParameterError(msg) if name in registry: return registry[name] if default is not MISSING: return default # Show all records that 'look like' name. # We don't dump the whole list, because it 1500+ items. msg = ("Cannot find a record with name '{name}'".format(name=name)) records = [key for key in registry.records.keys() if name in key] if records: msg = ('{message}\n' 'Did you mean?:\n' '{records}'.format(message=msg, records='\n'.join(records))) raise InvalidParameterError(msg)
def find_interface(resource, class_or_interface): # pylint:disable=inconsistent-return-statements """ Search for an object implementing *class_or_interface* in the :func:`lineage` of the *resource*. :param class_or_interface: Can be an interface or a concrete class to check with :func:`isinstance`. Deprecated, do not use. .. deprecated:: 1.0 This doesn't use the :class:`zope.location.interfaces.ILocationInfo` interface, and hence doesn't let the *resource* have customizations and ignores problems in the resource tree. """ if IInterface.providedBy(class_or_interface): test = class_or_interface.providedBy else: def test(arg): return isinstance(arg, class_or_interface) for location in lineage(resource): if test(location): return location
def get_workflow( content_type, type, context=None, process_wf_list=process_wf_list): # process_wf_list is for test """ Return a workflow based on a content_type, the workflow type, and (optionally) a context. The context is used as an argument to electors for placeful workflows.""" sm = getSiteManager() look = sm.adapters.lookup if not IInterface.providedBy(content_type): content_type = providedBy(content_type) if content_type not in (None, IDefaultWorkflow): wf_list = look((content_type, ), IWorkflowList, name=type, default=None) if wf_list is not None: wf = process_wf_list(wf_list, context) if wf is not None: return wf wf_list = look((IDefaultWorkflow, ), IWorkflowList, name=type, default=None) if wf_list is not None: return process_wf_list(wf_list, context)
def __init__(self, context, request): super(ModuleDetails, self).__init__(context, request) items = list(self.context.items()) items.sort() self.text_files = [] self.zcml_files = [] self.modules = [] self.interfaces = [] self.classes = [] self.functions = [] for name, obj in items: entry = {'name': name, 'url': absoluteURL(obj, self.request)} if IFunctionDocumentation.providedBy(obj): entry['doc'] = formatDocString( obj.getDocString(), self.context.getPath()) entry['signature'] = obj.getSignature() self.functions.append(entry) elif IModuleDocumentation.providedBy(obj): entry['doc'] = formatDocString( obj.getDocString(), obj.getPath(), True) self.modules.append(entry) elif IInterface.providedBy(obj): entry['path'] = getPythonPath(removeAllProxies(obj)) entry['doc'] = formatDocString( obj.__doc__, obj.__module__, True) self.interfaces.append(entry) elif IClassDocumentation.providedBy(obj): entry['doc'] = formatDocString( obj.getDocString(), self.context.getPath(), True) self.classes.append(entry) elif IZCMLFile.providedBy(obj): self.zcml_files.append(entry) elif ITextFile.providedBy(obj): self.text_files.append(entry)
def get_dotted_name(ob) -> str: if inspect.isclass(ob) or IInterface.providedBy(ob) or isinstance( ob, types.FunctionType): name = ob.__name__ else: name = ob.__class__.__name__ return ob.__module__ + '.' + name
def bind(self, schema): if not IInterface.providedBy(schema): raise TypeError("Cannot bind non-interface object %s" % schema) name = identify_interface(schema) if name in self._names: raise KeyError("duplicate schema: Interface %s already managed." % (name,)) self._names.append(name)
def provideAdapter(self, required, provided, name, factory, info=''): """Register an adapter >>> from zope.interface import Interface >>> registry = GlobalSiteManager() >>> class R1(Interface): ... pass >>> class R2(R1): ... pass >>> class P1(Interface): ... pass >>> class P2(P1): ... pass >>> registry.provideAdapter((R1, ), P2, 'bob', 'c1', 'd1') >>> registry.provideAdapter((R1, ), P2, '', 'c2', 'd2') >>> registry.adapters.lookup((R2, ), P1, '') 'c2' >>> registrations = map(repr, registry.registrations()) >>> registrations.sort() >>> for registration in registrations: ... print registration AdapterRegistration(('R1',), 'P2', '', 'c2', 'd2') AdapterRegistration(('R1',), 'P2', 'bob', 'c1', 'd1') Let's make sure that we can also register regular classes for adaptation. >>> class O1(object): ... pass >>> class O2(object): ... pass >>> class O3(object): ... def __init__(self, obj1, obj2=None): ... pass >>> registry.provideAdapter((O1, ), R1, '', O3) >>> registry.queryAdapter(O1(), R1, '').__class__ <class 'zope.component.site.O3'> >>> registry.provideAdapter((O1, O2), R1, '', O3) >>> registry.queryMultiAdapter((O1(), O2()), R1, '').__class__ <class 'zope.component.site.O3'> """ ifaces = [] for iface in required: if not IInterface.providedBy(iface) and iface is not None: if not isinstance(iface, (type, types.ClassType)): raise TypeError(iface, IInterface) iface = implementedBy(iface) ifaces.append(iface) required = tuple(ifaces) self._registrations[(required, provided, name)] = AdapterRegistration( required, provided, name, factory, info) self.adapters.register(required, provided, name, factory)
def factory(self, *args): if not args: raise TypeError("The omitted directive expects at least one argument.") form_interface = Interface if IInterface.providedBy(args[0]): form_interface = args[0] args = args[1:] return [(form_interface, field, self.value) for field in args]
def acquire(self, interface): node = self.parent while node: if (IInterface.providedBy(interface) and interface.providedBy(node)) or \ isinstance(node, interface): return node node = node.parent
def setBody(self, body, *args, **kw): if IInterface.providedBy(IStreamIterator): # is this zope 2.12? stream = IStreamIterator.providedBy(body) else: stream = IStreamIterator.isImplementedBy(body) if stream: body = ''.join(body) # read from iterator return self._original_setBody(body, *args, **kw)
def bind(self, schema): if not IInterface.providedBy(schema): raise TypeError('Cannot bind non-interface object %s' % schema) name = identify_interface(schema) if name in self._names: raise KeyError( 'duplicate schema: Interface %s already managed.' % (name,)) self._names.append(name)
def testFileBlobInterfaces(self): foo = self.folder[self.folder.invokeFactory('File', 'foo')] self.assertTrue(atfile.IATFile.providedBy(foo), 'no IATFile?') self.assertTrue(atfile.IFileContent.providedBy(foo), 'no IFileContent?') self.assertTrue(IATBlobFile.providedBy(foo), 'no IATBlobFile?') if not IInterface.providedBy(Z2IATFile): # this is zope < 2.12 self.assertTrue(Z2IATFile.isImplementedBy(foo), 'no zope2 IATFile?') self.assertFalse(Z2IATImage.isImplementedBy(foo), 'zope2 IATImage?')
def list_base_interfaces(interface): """List all interfaces regrouped by this one. """ if IInterface.providedBy(interface): yield interface for base in interface.__bases__: for base_base in list_base_interfaces(base): yield base_base
def execute(self, factory, config, context, **kw): if getattr(factory, 'schema', None) is None and \ IInterface.providedBy(context): factory.schema = context return True else: return False
def setBody(self, body, *args, **kw): if IInterface.providedBy(IStreamIterator): # is this zope 2.12? stream = IStreamIterator.providedBy(body) else: stream = IStreamIterator.isImplementedBy(body) if stream: body = ''.join(body) # read from iterator return original_setBody(self, body, *args, **kw)
def testImageBlobInterfaces(self): foo = self.folder[self.folder.invokeFactory('Image', 'foo')] self.failUnless(atimage.IATImage.providedBy(foo), 'no IATImage?') self.failUnless(atimage.IImageContent.providedBy(foo), 'no IImageContent?') self.failUnless(IATBlobImage.providedBy(foo), 'no IATBlobImage?') if not IInterface.providedBy(Z2IATFile): # this is zope < 2.12 self.failUnless(Z2IATImage.isImplementedBy(foo), 'no zope2 IATImage?') self.failIf(Z2IATFile.isImplementedBy(foo), 'zope2 IATFile?')
def __init__(self, schema, **kwargs): if IInterface.providedBy(schema): self.identifier = schema.__identifier__ else: self.identifier = str(schema) for name in getFieldNamesInOrder(interfaces.IFlavor): if name in kwargs: setattr(self, name, kwargs.get(name))
def add_content_provider(self, provider, name, context=None): """ Add content provider.""" if context is None: context = Interface if not IInterface.providedBy(context): context = implementedBy(context) self.registry.registerAdapter( provider, (context,), IContentProvider, name=name)
def _get(discriminator): """Get the TypeInfo instance for discriminator, that may be any of: type_key: str (the lowercase underscore-separated of domain cls name) workflow: an instance of Workflow, provides IWorkflow interface: provides IInterface domain model: provides IBungeniContent domain model instance: type provides IBungeniContent descriptor: provides IModelDescriptor Raise KeyError if no entry matched. Usage: capi.get_type_info(discriminator) """ if discriminator is None: m = "type_info._get discriminator is None" log.error(m) raise ValueError(m) discri = removeSecurityProxy(discriminator) getter = None # !+IALCHEMISTCONTENT normalize trickier discriminator cases to type_key if IIModelInterface.providedBy(discri): discri = naming.type_key("table_schema_interface_name", discri.__name__) elif IInterface.providedBy(discri): discri = naming.type_key("model_interface_name", discri.__name__) elif type(discri) is type and issubclass(discri, domain.Entity): discri = naming.polymorphic_identity(discri) elif isinstance(discri, domain.Entity): discri = naming.polymorphic_identity(type(discri)) if isinstance(discri, basestring): getter = _get_by_type_key #elif IInterface.providedBy(discri): # getter = _get_by_interface #!+elif interfaces.IBungeniContent.implementedBy(discri): #elif issubclass(discri, domain.Entity): # getter = _get_by_model #!+elif interfaces.IBungeniContent.providedBy(discri): #elif isinstance(discri, domain.Entity): # getter = _get_by_instance elif IWorkflow.providedBy(discri): getter = _get_by_workflow elif IModelDescriptor.implementedBy(discri): getter = _get_by_descriptor_model if getter is not None: ti = getter(discri) if ti is not None: return ti else: m = "No type registered for discriminator: %r" % (discriminator) else: m = "Invalid type info lookup discriminator: %r" % (discriminator) from bungeni.utils import probing log.debug(probing.interfaces(discriminator)) log.debug(m) raise KeyError(m)
def getInterfaceAllDocs(interface): iface_id = '%s.%s' % (interface.__module__, interface.__name__) docs = [str(iface_id).lower(), str(interface.__doc__).lower()] if IInterface.providedBy(interface): for name in sorted(interface): docs.append(str(interface.getDescriptionFor(name).__doc__).lower()) return '\n'.join(docs)
def iface_index(item): iface = item._for or Interface if IInterface.providedBy(iface): return ifaces.index(iface) if isinstance(removeSecurityProxy(object), item._for): # directly specified for class, this goes first. return -1 # no idea. This goes last. return max_key # pragma: no cover
def factory(self, *args): if not args: raise TypeError( 'The omitted directive expects at least one argument.') form_interface = Interface if IInterface.providedBy(args[0]): form_interface = args[0] args = args[1:] return [(form_interface, field, self.value) for field in args]
def find_resource_by_type(resource, path, class_or_interface): context = find_resource(resource, path) if IInterface.providedBy(class_or_interface): test = class_or_interface.providedBy else: test = lambda arg: isinstance(arg, class_or_interface) if not test(context): raise KeyError('%r type is not %s' % (context, class_or_interface)) return context
def applyTransformOnSuccess(event): """Apply the transform after a successful request """ transformed = applyTransform(event.request) if transformed is not None: response = event.request.response # horrid check to deal with Plone 3/Zope 2.10, where this is still an old-style interface if ((IInterface.providedBy(IStreamIterator) and IStreamIterator.providedBy(transformed)) or (not IInterface.providedBy(IStreamIterator) and IStreamIterator.isImplementedBy(transformed))): response.setBody(transformed) # setBody() can deal with byte and unicode strings (and will encode as necessary)... elif isinstance(transformed, basestring): response.setBody(transformed) # ... but not with iterables else: response.setBody(''.join(transformed))