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