本文整理汇总了Python中marshmallow.compat.iteritems函数的典型用法代码示例。如果您正苦于以下问题:Python iteritems函数的具体用法?Python iteritems怎么用?Python iteritems使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iteritems函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _serialize
def _serialize(self, value, attr, obj, **kwargs):
if value is None:
return None
if not self.value_container and not self.key_container:
return value
if not isinstance(value, collections.Mapping):
self.fail('invalid')
if self.key_container is None:
keys = {k: k for k in value.keys()}
else:
keys = {
k: self.key_container._serialize(k, None, None, **kwargs)
for k in value.keys()
}
if self.value_container is None:
result = collections.OrderedDict([(keys[k], v)
for k, v in iteritems(value) if k in keys])
else:
result = collections.OrderedDict([
(keys[k], self.value_container._serialize(v, None, None, **kwargs))
for k, v in iteritems(value)
])
return result
开发者ID:suryasr007,项目名称:RESTEasyCLI,代码行数:26,代码来源:common.py
示例2: format_item
def format_item(self, item):
"""Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
"""
ret = self.dict_class()
ret[TYPE] = self.opts.type_
# Get the schema attributes so we can confirm `dump-to` values exist
attributes = {
(self.fields[field].dump_to or field): field
for field in self.fields
}
for field_name, value in iteritems(item):
attribute = attributes[field_name]
if attribute == ID:
ret[ID] = value
elif isinstance(self.fields[attribute], BaseRelationship):
if 'relationships' not in ret:
ret['relationships'] = self.dict_class()
ret['relationships'][self.inflect(field_name)] = value
else:
if 'attributes' not in ret:
ret['attributes'] = self.dict_class()
ret['attributes'][self.inflect(field_name)] = value
links = self.get_resource_links(item)
if links:
ret['links'] = links
return ret
开发者ID:jaypatel16,项目名称:jaytest,代码行数:31,代码来源:schema.py
示例3: get_field_names_for_argmap
def get_field_names_for_argmap(argmap):
if isinstance(argmap, ma.Schema):
all_field_names = set([fname for fname, fobj in iteritems(argmap.fields)
if not fobj.dump_only])
else:
all_field_names = set(argmap.keys())
return all_field_names
开发者ID:gh0std4ncer,项目名称:nzbhydra,代码行数:7,代码来源:core.py
示例4: marshal
def marshal(self, data, fields_dict, many=False):
"""Takes raw data (a dict, list, or other object) and a dict of
fields to output and filters the data based on those fields.
:param data: The actual object(s) from which the fields are taken from
:param dict fields: A dict whose keys will make up the final serialized
response output.
:param bool many: Set to ``True`` if ``data`` is a collection object
that is iterable.
:returns: An OrderedDict of the marshalled data
"""
if many and data is not None:
return [self.marshal(d, fields_dict, many=False) for d in data]
items = []
for attr_name, field_obj in iteritems(fields_dict):
key = self.prefix + attr_name
try:
item = (key, field_obj.output(attr_name, data))
except MarshallingError as err: # Store errors
if self.strict:
raise err
self.errors[key] = text_type(err)
item = (key, None)
except TypeError:
# field declared as a class, not an instance
if isinstance(field_obj, type) and \
issubclass(field_obj, FieldABC):
msg = ('Field for "{0}" must be declared as a '
"Field instance, not a class. "
'Did you mean "fields.{1}()"?'
.format(attr_name, field_obj.__name__))
raise TypeError(msg)
raise
items.append(item)
return OrderedDict(items)
开发者ID:kalasjocke,项目名称:marshmallow,代码行数:35,代码来源:fields.py
示例5: marshal
def marshal(self, data, fields_dict):
"""Takes the data (a dict, list, or object) and a dict of fields.
Stores any errors that occur.
:param data: The actual object(s) from which the fields are taken from
:param dict fields_dict: A dict whose keys will make up the final serialized
response output
"""
if utils.is_collection(data):
return [self.marshal(d, fields_dict) for d in data]
items = []
for attr_name, field_obj in iteritems(fields_dict):
key = self.prefix + attr_name
try:
if isinstance(field_obj, dict):
item = (key, self.marshal(data, field_obj))
else:
try:
item = (key, field_obj.output(attr_name, data))
except TypeError:
# field declared as a class, not an instance
if issubclass(field_obj, base.FieldABC):
msg = ('Field for "{0}" must be declared as a '
"Field instance, not a class. "
'Did you mean "fields.{1}()"?'
.format(attr_name, field_obj.__name__))
raise TypeError(msg)
raise
except exceptions.MarshallingError as err: # Store errors
if self.strict or self.opts.strict:
raise err
self.errors[key] = text_type(err)
item = (key, None)
items.append(item)
return OrderedDict(items)
开发者ID:jhardies,项目名称:marshmallow,代码行数:35,代码来源:serializer.py
示例6: _parse_request
def _parse_request(self, argmap, req, locations):
argdict = argmap.fields if isinstance(argmap, ma.Schema) else argmap
parsed = {}
for argname, field_obj in iteritems(argdict):
pass
pass
return parsed
开发者ID:gspu,项目名称:nzbhydra,代码行数:7,代码来源:async.py
示例7: _serialize
def _serialize(self, value, key, obj):
"""Output the URL for the endpoint, given the kwargs passed to
``__init__``.
"""
param_values = {}
for name, attr_tpl in iteritems(self.params):
attr_name = _tpl(str(attr_tpl))
if attr_name:
attribute_value = utils.get_value(attr_name, obj, default=missing)
if attribute_value is not missing:
param_values[name] = attribute_value
else:
err = AttributeError(
'{attr_name!r} is not a valid '
'attribute of {obj!r}'.format(attr_name=attr_name, obj=obj)
)
if has_forced_error:
raise ForcedError(err)
else:
raise err
else:
param_values[name] = attr_tpl
try:
return url_for(self.endpoint, **param_values)
except BuildError as err: # Make sure BuildErrors are raised
if has_forced_error:
raise ForcedError(err)
else:
raise err
开发者ID:exuusdevteam,项目名称:asprin,代码行数:29,代码来源:fields.py
示例8: __set_field_attrs
def __set_field_attrs(self, fields_dict):
"""Bind fields to the schema, setting any necessary attributes
on the fields (e.g. parent and name).
Also set field load_only and dump_only values if field_name was
specified in ``class Meta``.
"""
for field_name, field_obj in iteritems(fields_dict):
try:
if field_name in self.load_only:
field_obj.load_only = True
if field_name in self.dump_only:
field_obj.dump_only = True
field_obj._add_to_schema(field_name, self)
self.on_bind_field(field_name, field_obj)
except TypeError:
# field declared as a class, not an instance
if (isinstance(field_obj, type) and
issubclass(field_obj, base.FieldABC)):
msg = ('Field for "{0}" must be declared as a '
'Field instance, not a class. '
'Did you mean "fields.{1}()"?'
.format(field_name, field_obj.__name__))
raise TypeError(msg)
return fields_dict
开发者ID:exuusdevteam,项目名称:asprin,代码行数:25,代码来源:schema.py
示例9: _parse_request
def _parse_request(self, argmap, req, locations):
argdict = argmap.fields if isinstance(argmap, ma.Schema) else argmap
parsed = {}
for argname, field_obj in iteritems(argdict):
parsed_value = self.parse_arg(argname, field_obj, req,
locations=locations or self.locations)
parsed[argname] = parsed_value
return parsed
开发者ID:gh0std4ncer,项目名称:nzbhydra,代码行数:8,代码来源:core.py
示例10: _parse_request
def _parse_request(self, schema, req, locations):
argdict = schema.fields
parsed = {}
for argname, field_obj in iteritems(argdict):
parsed_value = yield from self.parse_arg(argname, field_obj, req,
locations=locations or self.locations)
parsed[argname] = parsed_value
return parsed
开发者ID:NSConfArg,项目名称:NSOperations,代码行数:8,代码来源:async.py
示例11: unwrap_item
def unwrap_item(self, item):
if 'type' not in item:
raise ma.ValidationError([
{
'detail': '`data` object must include `type` key.',
'pointer': '/data'
}
])
if item['type'] != self.opts.type_:
raise IncorrectTypeError(actual=item['type'], expected=self.opts.type_)
payload = self.dict_class()
if 'id' in item:
payload['id'] = item['id']
for key, value in iteritems(item.get('attributes', {})):
payload[key] = value
for key, value in iteritems(item.get('relationships', {})):
payload[key] = value
return payload
开发者ID:Tim-Erwin,项目名称:marshmallow-jsonapi,代码行数:19,代码来源:schema.py
示例12: format_errors
def format_errors(self, errors, many):
"""Format validation errors as JSON Error objects."""
if not errors:
return {}
formatted_errors = []
if many:
for index, errors in iteritems(errors):
for field_name, field_errors in iteritems(errors):
formatted_errors.extend([
self.format_error(field_name, message, index=index)
for message in field_errors
])
else:
for field_name, field_errors in iteritems(errors):
formatted_errors.extend([
self.format_error(field_name, message)
for message in field_errors
])
return {'errors': formatted_errors}
开发者ID:rmoorman,项目名称:marshmallow-jsonapi,代码行数:20,代码来源:schema.py
示例13: _rapply
def _rapply(d, func, *args, **kwargs):
"""Apply a function to all values in a dictionary or list of dictionaries, recursively."""
if isinstance(d, (tuple, list)):
return [_rapply(each, func, *args, **kwargs) for each in d]
if isinstance(d, dict):
return {
key: _rapply(value, func, *args, **kwargs)
for key, value in iteritems(d)
}
else:
return func(d, *args, **kwargs)
开发者ID:exuusdevteam,项目名称:asprin,代码行数:11,代码来源:fields.py
示例14: make_instance
def make_instance(self, data):
"""Deserialize data to an instance of the model. Update an existing row
if specified in `self.instance` or loaded by primary key(s) in the data;
else create a new row.
:param data: Data to deserialize.
"""
instance = self.instance or self.get_instance(data)
if instance is not None:
for key, value in iteritems(data):
setattr(instance, key, value)
return instance
return self.opts.model(**data)
开发者ID:RaminFP,项目名称:PYHelper,代码行数:13,代码来源:schema.py
示例15: __set_field_attrs
def __set_field_attrs(self, fields_dict):
"""Set the parents of all field objects in fields_dict to self, and
set the dateformat specified in ``class Meta``, if necessary.
"""
for field_name, field_obj in iteritems(fields_dict):
if not field_obj.parent:
field_obj.parent = self
if not field_obj.name:
field_obj.name = field_name
if isinstance(field_obj, fields.DateTime):
if field_obj.dateformat is None:
field_obj.dateformat = self.opts.dateformat
return fields_dict
开发者ID:svenstaro,项目名称:marshmallow,代码行数:13,代码来源:schema.py
示例16: _deserialize
def _deserialize(self, value, attr, data, **kwargs):
if not isinstance(value, collections.Mapping):
self.fail('invalid')
if not self.value_container and not self.key_container:
return value
errors = collections.defaultdict(dict)
if self.key_container is None:
keys = {k: k for k in value.keys()}
else:
keys = {}
for key in value.keys():
try:
keys[key] = self.key_container.deserialize(key)
except ValidationError as error:
errors[key]['key'] = error.messages
if self.value_container is None:
result = collections.OrderedDict([(keys[k], v) for k, v in iteritems(value) if k in keys])
else:
result = collections.OrderedDict()
for key, val in iteritems(value):
try:
deser_val = self.value_container.deserialize(val)
except ValidationError as error:
errors[key]['value'] = error.messages
if error.valid_data is not None and key in keys:
result[keys[key]] = error.valid_data
else:
if key in keys:
result[keys[key]] = deser_val
if errors:
raise ValidationError(errors, valid_data=result)
return result
开发者ID:suryasr007,项目名称:RESTEasyCLI,代码行数:37,代码来源:common.py
示例17: _get_fields
def _get_fields(attrs, field_class, pop=False):
"""Get fields from a class, sorted by creation index.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields
"""
getter = getattr(attrs, 'pop' if pop else 'get')
return sorted(
[
(field_name, getter(field_name))
for field_name, field_value in list(iteritems(attrs))
if utils.is_instance_or_subclass(field_value, field_class)
],
key=lambda pair: pair[1]._creation_index,
)
开发者ID:svenstaro,项目名称:marshmallow,代码行数:16,代码来源:schema.py
示例18: get_declared_fields
def get_declared_fields(mcs, bases, attrs, field_class):
'''Return the declared fields of a class as an OrderedDict.
:param tuple bases: Tuple of classes the class is subclassing.
:param dict attrs: Dictionary of class attributes.
:param type field_class: The base field class. Any class attribute that
is of this type will be be returned
'''
declared = [(field_name, attrs.pop(field_name))
for field_name, val in list(iteritems(attrs))
if utils.is_instance_or_subclass(val, field_class)]
# If subclassing another Serializer, inherit its fields
# Loop in reverse to maintain the correct field order
for base_class in bases[::-1]:
if hasattr(base_class, '_declared_fields'):
declared = list(base_class._declared_fields.items()) + declared
return OrderedDict(declared)
开发者ID:asteinlein,项目名称:marshmallow,代码行数:17,代码来源:serializer.py
示例19: resolve_params
def resolve_params(obj, params):
"""Given a dictionary of keyword arguments, return the same dictionary except with
values enclosed in `< >` resolved to attributes on `obj`.
"""
param_values = {}
for name, attr_tpl in iteritems(params):
attr_name = tpl(str(attr_tpl))
if attr_name:
attribute_value = get_value(attr_name, obj, default=missing)
if attribute_value is not missing:
param_values[name] = attribute_value
else:
raise AttributeError(
'{attr_name!r} is not a valid '
'attribute of {obj!r}'.format(attr_name=attr_name, obj=obj)
)
else:
param_values[name] = attr_tpl
return param_values
开发者ID:Tim-Erwin,项目名称:marshmallow-jsonapi,代码行数:19,代码来源:utils.py
示例20: format_item
def format_item(self, item):
"""Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
"""
ret = self.dict_class()
type_ = self.opts.type_
ret[TYPE] = type_
for field_name, value in iteritems(item):
if field_name == ID:
ret[ID] = value
elif isinstance(self.fields[field_name], BaseRelationship):
if 'relationships' not in ret:
ret['relationships'] = self.dict_class()
ret['relationships'].update(value)
else:
if 'attributes' not in ret:
ret['attributes'] = self.dict_class()
ret['attributes'][self.inflect(field_name)] = value
return ret
开发者ID:rmoorman,项目名称:marshmallow-jsonapi,代码行数:20,代码来源:schema.py
注:本文中的marshmallow.compat.iteritems函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论