• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python interfaces.ICollection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中zope.schema.interfaces.ICollection的典型用法代码示例。如果您正苦于以下问题:Python ICollection类的具体用法?Python ICollection怎么用?Python ICollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ICollection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_collection_schema_from_interface_schema

 def get_collection_schema_from_interface_schema(self, schema):
     collection = {}
     for name in schema:
         if IDate.providedBy(schema[name]) or \
                                             IDatetime.providedBy(schema[name]):
             collection['field.'+name] = 'time'
         elif IDecimal.providedBy(schema[name]) or \
                             IFloat.providedBy(schema[name]) or \
                                            IInt.providedBy(schema[name]):
             collection['field.'+name] = 'number'
         elif IBool.providedBy(schema[name]):
             collection['field.'+name] = 'bool'
         elif ICollection.providedBy(schema[name]):
             if not ICollection.providedBy(schema[name].value_type) and not \
                         IDict.providedBy(schema[name].value_type):
                 collection['field.'+name] = 'array'
         elif IDict.providedBy(schema[name]):
             if IText.providedBy(schema[name].key_type) and \
                         IText.providedBy(schema[name].value_type):
                 collection['field.'+name] = 'array'
         # this is a pretty weak check for a IP address field.  We might want
         # to update this to look for a field validator based on the ipaddress package
         # or mark this field with a special interface indicating it is an 
         # IP address
         elif IDottedName.providedBy(schema[name]) and \
                         (schema[name].min_dots == schema[name].max_dots == 3):
             collection['field.'+name] = 'cidr'
         elif IText.providedBy(schema[name]) or \
                                     INativeString.providedBy(schema[name]):
             collection['field.'+name] = 'string'
     return collection
开发者ID:davisd50,项目名称:sparc.db,代码行数:31,代码来源:kvstore.py


示例2: elementToValue

def elementToValue(field, element, default=_marker):
    """Read the contents of an element that is assumed to represent a value
    allowable by the given field.

    If converter is given, it should be an IToUnicode instance.

    If not, the field will be adapted to this interface to obtain a converter.
    """
    value = default

    if IDict.providedBy(field):
        key_converter = IFromUnicode(field.key_type)
        value = OrderedDict()
        for child in element.iterchildren(tag=etree.Element):
            if noNS(child.tag.lower()) != 'element':
                continue
            parseinfo.stack.append(child)

            key_text = child.attrib.get('key', None)
            if key_text is None:
                k = None
            else:
                k = key_converter.fromUnicode(unicode(key_text))

            value[k] = elementToValue(field.value_type, child)
            parseinfo.stack.pop()
        value = fieldTypecast(field, value)

    elif ICollection.providedBy(field):
        value = []
        for child in element.iterchildren(tag=etree.Element):
            if noNS(child.tag.lower()) != 'element':
                continue
            parseinfo.stack.append(child)
            v = elementToValue(field.value_type, child)
            value.append(v)
            parseinfo.stack.pop()
        value = fieldTypecast(field, value)

    # Unicode
    else:
        text = element.text
        if text is None:
            value = field.missing_value
        else:
            converter = IFromUnicode(field)
            value = converter.fromUnicode(unicode(text))

        # handle i18n
        if isinstance(value, unicode) and parseinfo.i18n_domain is not None:
            translate_attr = ns('translate', I18N_NAMESPACE)
            domain_attr = ns('domain', I18N_NAMESPACE)
            msgid = element.attrib.get(translate_attr)
            domain = element.attrib.get(domain_attr, parseinfo.i18n_domain)
            if msgid:
                value = Message(msgid, domain=domain, default=value)
            elif translate_attr in element.attrib:
                value = Message(value, domain=domain)

    return value
开发者ID:CGTIC,项目名称:Plone_SP,代码行数:60,代码来源:utils.py


示例3: import_node

    def import_node(self, interface, child):
        """Import a single <property /> node
        """
        property_name = child.getAttribute('name')

        field = interface.get(property_name, None)
        if field is None:
            return

        field = field.bind(self.element)
        value = None

        # If we have a collection, we need to look at the value_type.
        # We look for <element>value</element> child nodes and get the
        # value from there
        if ICollection.providedBy(field):
            value_type = field.value_type
            value = []
            for element in child.childNodes:
                if element.nodeName != 'element':
                    continue
                element_value = self.extract_text(element)
                value.append(self.from_unicode(value_type, element_value))
            value = self.field_typecast(field, value)

        # Otherwise, just get the value of the <property /> node
        else:
            value = self.extract_text(child)
            value = self.from_unicode(field, value)

        field.validate(value)
        field.set(self.element, value)
开发者ID:alecghica,项目名称:plone.app.contentrules,代码行数:32,代码来源:rules.py


示例4: import_node_for_field

 def import_node_for_field(self, field, child):
     value = None
     
     # If we have a collection, we need to look at the value_type.
     # We look for <element>value</element> child nodes and get the
     # value from there
     if ICollection.providedBy(field):
         value_type = field.value_type
         value = []
         for element in child.childNodes:
             if element.nodeName != 'element':
                 continue
             value.append(self.import_node_for_field(value_type, element))
     elif IObject.providedBy(field):
         value = {}
         for element in child.childNodes:
             if element.nodeName != 'property':
                 continue
             property_key = self.extract_text(element.attributes['name'])
             property_value = self.import_node_for_field(field.schema[property_key], element)
             value[property_key] = property_value
     elif IChoice.providedBy(field):
         # Choice fields can be optional, so treat an empty contents as None
         value = self.extract_text(child)
         if not value:
             value = None
         else:
             value = self.from_unicode(field, value)
     else:
         # Otherwise, just get the value of the <property /> node
         value = self.extract_text(child)
         if not (field.getName() == 'root' and value in ['', '/']):
             value = self.from_unicode(field, value)
     value = self.field_typecast(field, value)
     return value
开发者ID:CGTIC,项目名称:Plone_SP,代码行数:35,代码来源:portlets.py


示例5: __getattr__

 def __getattr__(self, name):
     reg = self.__registry__
     if name not in self.__schema__:
         raise AttributeError(name)
     field = self.__schema__.get(name)
     if IObject.providedBy(field):
         iface = field.schema
         collection = reg.collectionOfInterface(
                         iface,
                         check=False,
                         factory=ComplexRecordsProxy)
         if collection.has_key(name):
             value = collection[name]
         else:
             value = _marker
     elif ICollection.providedBy(field) and \
             IObject.providedBy(field.value_type):
         iface = field.value_type.schema
         coll_prefix = iface.__identifier__ + '.' + name
         collection = reg.collectionOfInterface(
                         iface,
                         check=False,
                         prefix=coll_prefix,
                         factory=ComplexRecordsProxy)
         value = collection.values()
         if not value:
             value = _marker
     else:
         value = reg.get(self.__prefix__ + name, _marker)
     if value is _marker:
         value = self.__schema__[name].missing_value
     return value
开发者ID:collective,项目名称:collective.complexrecordsproxy,代码行数:32,代码来源:complexrecordsproxy.py


示例6: __setattr__

 def __setattr__(self, name, value):
     if name in self.__schema__:
         reg = self.__registry__
         field = self.__schema__.get(name)
         if IObject.providedBy(field):
             iface = field.schema
             collection = reg.collectionOfInterface(
                             iface,
                             check=False,
                             factory=ComplexRecordsProxy)
             collection[name] = value
         elif ICollection.providedBy(field) and \
                 IObject.providedBy(field.value_type):
             iface = field.value_type.schema
             # All tuple items are stored as records under
             # the coll_prefix prefix:
             coll_prefix = iface.__identifier__ + '.' + name
             collection = reg.collectionOfInterface(
                             iface,
                             check=False,
                             prefix=coll_prefix,
                             factory=ComplexRecordsProxy)
             # Clear collection before adding/updating in case of deletes.
             collection.clear()
             for idx, val in enumerate(value):
                 # val is our obj created by the z3cform factory
                 collection['r' + str(idx)] = val
         else:
             full_name = self.__prefix__ + name
             if full_name not in reg:
                 raise AttributeError(name)
             reg[full_name] = value
     else:
         self.__dict__[name] = value
开发者ID:collective,项目名称:collective.complexrecordsproxy,代码行数:34,代码来源:complexrecordsproxy.py


示例7: import_node

    def import_node(self, interface, child):
        """Import a single <property /> node
        """
        property_name = child.getAttribute('name')

        field = interface.get(property_name, None)
        if field is None:
            return

        field = field.bind(self.assignment)
        value = None

        # If we have a collection, we need to look at the value_type.
        # We look for <element>value</element> child nodes and get the
        # value from there
        if ICollection.providedBy(field):
            value_type = field.value_type
            value = []
            for element in child.childNodes:
                if element.nodeName != 'element':
                    continue
                element_value = self.extract_text(element)
                value.append(self.from_unicode(value_type, element_value))
            value = self.field_typecast(field, value)

        # Otherwise, just get the value of the <property /> node
        else:
            value = self.extract_text(child)
            value = self.from_unicode(field, value)

        try:
            field.validate(value)
        except ConstraintNotSatisfied, e:
            logger.warning('"%s" value doesn\'t satisfy constaints for "%s:%s" field' % \
                (value, self.assignment.__name__, field.__name__))
开发者ID:chaoflow,项目名称:quintagroup.transmogrifier,代码行数:35,代码来源:portlets.py


示例8: field_info

 def field_info(self, field):
     is_col = ICollection.providedBy(field)
     vtype = field.value_type.__class__.__name__ if is_col else None
     return {
         'name': field.__name__,
         'title': field.title,
         'type': field.__class__.__name__,
         'value_type': vtype
         }
开发者ID:upiq,项目名称:uu.formlibrary,代码行数:9,代码来源:multi.py


示例9: schema_type

def schema_type(description):
    name = description.__class__.__name__
    modulename = description.__class__.__module__
    if modulename.startswith('zope.schema'):
        # We hide the _bootstrap
        modulename = 'zope.schema'
    field_type = ':py:class:`%s<%s.%s>`' % (name, modulename, name)
    if ICollection.providedBy(description):
        field_type += ' of %s' % schema_type(description.value_type)
    return field_type
开发者ID:infrae,项目名称:sphinxcontrib.infrae,代码行数:10,代码来源:autointerface.py


示例10: test_fieldref_interfaces

    def test_fieldref_interfaces(self):
        from plone.registry import field, FieldRef
        from plone.registry.interfaces import IFieldRef
        from zope.schema.interfaces import ICollection

        listField = field.List(value_type=field.ASCIILine())
        ref = FieldRef('some.record', listField)

        self.assertTrue(ICollection.providedBy(ref))
        self.assertTrue(IFieldRef.providedBy(ref))
开发者ID:pyrenees,项目名称:plone.registry,代码行数:10,代码来源:tests.py


示例11: initialize

    def initialize(self):
        """Initialize the view class."""
        fieldId = self.request.get('fieldId','').split('-')[-1]
        typeOrDottedname = self.request.get('typeOrDottedname')
        context = aq_inner(self.context)
        if typeOrDottedname == context.portal_type and shasattr(context, 'Schema'):
            # Archetype
            field = context.Schema().getField(fieldId)
            self.multivalued = field.multiValued
            self.widget = field.widget
        else: 
            fti = queryUtility(IDexterityFTI, name=typeOrDottedname)
            if fti is None:
                # Must be a standalone z3c.form forms then.
                klass = utils.resolveDottedName(typeOrDottedname)
                field = klass(self.context, self.request).fields.get(fieldId).field
                self.widget = FieldWidget(field, UserAndGroupSelectionWidget(field, self.request))
                self.multivalued = ICollection.providedBy(field)
            else:
                # Dexterity
                schema = fti.lookupSchema()
                field = schema.get(fieldId)
                if field is None:
                    # The field might be defined in a behavior schema.
                    # Get the behaviors from either the context or the
                    # portal_type (but not both at the same time).
                    if self.request.get('ignoreContext'):
                        context = None
                        portal_type = typeOrDottedname
                    else:
                        portal_type = None
                    for behavior_schema in \
                            utils.getAdditionalSchemata(context, portal_type):
                        if behavior_schema is not None:
                            field = behavior_schema.get(fieldId)
                            if field is not None:
                                    break
                self.widget = FieldWidget(field, UserAndGroupSelectionWidget(field, self.request))
                self.multivalued = ICollection.providedBy(field)

        self.memberlookup = MemberLookup(self.context,
                                         self.request,
                                         self.widget)
开发者ID:alecghica,项目名称:Products.UserAndGroupSelectionWidget,代码行数:43,代码来源:browser.py


示例12: _base_args

    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """

        args = super(AjaxSelectWidget, self)._base_args()

        args["name"] = self.name
        args["value"] = self.value

        args.setdefault("pattern_options", {})

        field_name = self.field and self.field.__name__ or None

        context = self.context
        # We need special handling for AddForms
        if IAddForm.providedBy(getattr(self, "form")):
            context = self.form

        vocabulary_name = self.vocabulary
        field = None
        if IChoice.providedBy(self.field):
            args["pattern_options"]["maximumSelectionSize"] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type
        if not vocabulary_name and field is not None:
            vocabulary_name = field.vocabularyName

        args["pattern_options"] = dict_merge(
            get_ajaxselect_options(
                context, args["value"], self.separator, vocabulary_name, self.vocabulary_view, field_name
            ),
            args["pattern_options"],
        )

        if field and getattr(field, "vocabulary", None):
            form_url = self.request.getURL()
            source_url = "%s/++widget++%s/@@getSource" % (form_url, self.name)
            args["pattern_options"]["vocabularyUrl"] = source_url

        # ISequence represents an orderable collection
        if ISequence.providedBy(self.field) or self.orderable:
            args["pattern_options"]["orderable"] = True

        return args
开发者ID:hoka,项目名称:plone.app.widgets,代码行数:54,代码来源:dx.py


示例13: _indexer_value

def _indexer_value(v, fieldtype=None):
    """General value normalizer for indexed values"""
    # check datetime, then date, order matters:
    if isinstance(v, datetime.datetime):
        return int(time.mktime(v.timetuple()))  # timetuple has 1s resolution
    if isinstance(v, datetime.date):
        return v.toordinal()
    if v is None and ICollection.implementedBy(fieldtype):
        # default value is empty list/set/tuple/dict respective to fieldtype
        return fieldtype._type()  # _type is non-tuple type for collections
    elif v is None:
        # avoid range query side effects of None key for index btrees
        return float('inf')  # sentinel value
    return v
开发者ID:upiq,项目名称:uu.retrieval,代码行数:14,代码来源:catalog.py


示例14: _base_args

    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(RelatedItemsWidget, self)._base_args()

        args['name'] = self.name
        args['value'] = self.value
        args.setdefault('pattern_options', {})

        field = None
        if IChoice.providedBy(self.field):
            args['pattern_options']['maximumSelectionSize'] = 1
            field = self.field
        elif ICollection.providedBy(self.field):
            field = self.field.value_type

        vocabulary_name = self.vocabulary
        if not vocabulary_name:
            if field is not None and field.vocabularyName:
                vocabulary_name = field.vocabularyName
            else:
                vocabulary_name = 'plone.app.vocabularies.Catalog'

        field_name = self.field and self.field.__name__ or None
        args['pattern_options'] = dict_merge(
            get_relateditems_options(self.context, args['value'],
                                     self.separator, vocabulary_name,
                                     self.vocabulary_view, field_name),
            args['pattern_options'])

        if not self.vocabulary:  # widget vocab takes precedence over field
            if field and getattr(field, 'vocabulary', None):
                form_url = self.request.getURL()
                source_url = "%s/++widget++%s/@@getSource" % (
                    form_url, self.name)
                args['pattern_options']['vocabularyUrl'] = source_url

        return args
开发者ID:pigeonflight,项目名称:plone.app.widgets,代码行数:47,代码来源:dx.py


示例15: _base_args

    def _base_args(self):
        """Method which will calculate _base class arguments.

        Returns (as python dictionary):
            - `pattern`: pattern name
            - `pattern_options`: pattern options
            - `name`: field name
            - `value`: field value
            - `multiple`: field multiple
            - `items`: field items from which we can select to

        :returns: Arguments which will be passed to _base
        :rtype: dict
        """
        args = super(SelectWidget, self)._base_args()
        args['name'] = self.name
        args['value'] = self.value
        args['multiple'] = self.multiple

        self.required = self.field.required

        options = args.setdefault('pattern_options', {})
        if self.multiple or ICollection.providedBy(self.field):
            options['multiple'] = args['multiple'] = self.multiple = True

        # ISequence represents an orderable collection
        if ISequence.providedBy(self.field) or self.orderable:
            options['orderable'] = True

        if self.multiple:
            options['separator'] = self.separator

        # Allow to clear field value if it is not required
        if not self.required:
            options['allowClear'] = True

        items = []
        for item in self.items():
            if not isinstance(item['content'], basestring):
                item['content'] = translate(
                    item['content'],
                    context=self.request,
                    default=item['value'])
            items.append((item['value'], item['content']))
        args['items'] = items

        return args
开发者ID:athomerson,项目名称:plone.app.z3cform,代码行数:47,代码来源:widget.py


示例16: get_vocabulary

    def get_vocabulary(self):
        widget = self.context
        field = widget.field.bind(widget.context)

        # check field's write permission
        info = mergedTaggedValueDict(field.interface, WRITE_PERMISSIONS_KEY)
        permission_name = info.get(field.__name__, "cmf.ModifyPortalContent")
        permission = queryUtility(IPermission, name=permission_name)
        if permission is None:
            permission = getUtility(IPermission, name="cmf.ModifyPortalContent")
        if not getSecurityManager().checkPermission(permission.title, self.get_context()):
            raise VocabLookupException("Vocabulary lookup not allowed.")

        if ICollection.providedBy(field):
            return field.value_type.vocabulary
        else:
            return field.vocabulary
开发者ID:fgrcon,项目名称:plone.app.content,代码行数:17,代码来源:vocabulary.py


示例17: elementToValue

def elementToValue(field, element, default=_marker):
    """Read the contents of an element that is assumed to represent a value
    allowable by the given field.

    If converter is given, it should be an IToUnicode instance.

    If not, the field will be adapted to this interface to obtain a converter.
    """

    value = default

    if IDict.providedBy(field):
        key_converter = IFromUnicode(field.key_type)
        value = {}
        for child in element:
            if noNS(child.tag.lower()) != 'element':
                continue

            key_text = child.attrib.get('key', None)
            if key_text is None:
                k = None
            else:
                k = key_converter.fromUnicode(unicode(key_text))

            value[k] = elementToValue(field.value_type, child)
        value = fieldTypecast(field, value)

    elif ICollection.providedBy(field):
        value = []
        for child in element:
            if noNS(child.tag.lower()) != 'element':
                continue
            v = elementToValue(field.value_type, child)
            value.append(v)
        value = fieldTypecast(field, value)

    # Unicode
    else:
        text = element.text
        if text is None:
            value = field.missing_value
        else:
            converter = IFromUnicode(field)
            value = converter.fromUnicode(unicode(text))

    return value
开发者ID:jsbueno,项目名称:plone.supermodel,代码行数:46,代码来源:utils.py


示例18: import_node

    def import_node(self, interface, child):
        """Import a single <property /> node
        """
        property_name = child.getAttribute('name')

        field = interface.get(property_name, None)
        if field is None:
            return

        field = field.bind(self.assignment)
        value = None

        # If we have a collection, we need to look at the value_type.
        # We look for <element>value</element> child nodes and get the
        # value from there
        if ICollection.providedBy(field):
            value_type = field.value_type
            value = []
            for element in child.childNodes:
                if element.nodeName != 'element':
                    continue
                element_value = self.extract_text(element)
                value.append(self.from_unicode(value_type, element_value))
            value = self.field_typecast(field, value)

        # Otherwise, just get the value of the <property /> node
        else:
            value = self.extract_text(child)
            if not (field.getName() == 'root' and value in ['', '/']):
                value = self.from_unicode(field, value)

        if field.getName() == 'root' and value in ['', '/']:
            # these valid values don't pass validation of SearchableTextSourceBinder
            field.set(self.assignment, value)
        else:
            # I don't care if it's raised on a path...
            try:
                field.validate(value)
            except ConstraintNotSatisfied:
                if type(field) == Choice and ISource.providedBy(field.source):
                    pass
                else:
                    raise
            field.set(self.assignment, value)
开发者ID:collective,项目名称:wildcard.migrator,代码行数:44,代码来源:portlets.py


示例19: export_field

    def export_field(self, doc, field):
        """Turn a zope.schema field into a node and return it
        """
        field = field.bind(self.assignment)
        value = field.get(self.assignment)

        child = doc.createElement('property')
        child.setAttribute('name', field.__name__)

        if value is not None:
            if ICollection.providedBy(field):
                for e in value:
                    list_element = doc.createElement('element')
                    list_element.appendChild(doc.createTextNode(str(e)))
                    child.appendChild(list_element)
            else:
                child.appendChild(doc.createTextNode(unicode(value)))

        return child
开发者ID:SyZn,项目名称:plone.app.portlets,代码行数:19,代码来源:portlets.py


示例20: export_sub_field

    def export_sub_field(self, doc, parent, field, value):
        """Turn a zope.schema field into a node and return it
        """
        if value is not None:
            if ICollection.providedBy(field):
                for e in value:
                    list_element = doc.createElement('element')
                    self.export_sub_field(doc, list_element, field.value_type, e)
                    parent.appendChild(list_element)
            elif IObject.providedBy(field):
                for name, sub_field in field.schema.namesAndDescriptions():
                    sub_value = value.get(name)
                    list_element = doc.createElement('property')
                    list_element.setAttribute('name', name)
                    self.export_sub_field(doc, list_element, sub_field, sub_value)
                    parent.appendChild(list_element)
            else:
                parent.appendChild(doc.createTextNode(unicode(value)))

        return parent
开发者ID:CGTIC,项目名称:Plone_SP,代码行数:20,代码来源:portlets.py



注:本文中的zope.schema.interfaces.ICollection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python interfaces.IContextSourceBinder类代码示例发布时间:2022-05-26
下一篇:
Python interfaces.IChoice类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap