本文整理汇总了Python中zope.schema.interfaces.ICollection类的典型用法代码示例。如果您正苦于以下问题:Python ICollection类的具体用法?Python ICollection怎么用?Python ICollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ICollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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)
示例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
示例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
示例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
示例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__))
示例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
}
示例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
示例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))
示例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)
示例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
示例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
示例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
示例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