本文整理匯總了Python中rest_framework.compat.OrderedDict類的典型用法代碼示例。如果您正苦於以下問題:Python OrderedDict類的具體用法?Python OrderedDict怎麽用?Python OrderedDict使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了OrderedDict類的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _merge_fields_and_pk
def _merge_fields_and_pk(pk, fields):
fields_and_pk = OrderedDict()
fields_and_pk['pk'] = pk
fields_and_pk[pk.name] = pk
fields_and_pk.update(fields)
return fields_and_pk
示例2: get_field_info
def get_field_info(self, field):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', False)
attrs = [
'read_only', 'label', 'help_text',
'min_length', 'max_length',
'min_value', 'max_value'
]
for attr in attrs:
value = getattr(field, attr, None)
if value is not None and value != '':
field_info[attr] = force_text(value, strings_only=True)
if not field_info.get('read_only') and hasattr(field, 'choices'):
field_info['choices'] = [
{
'value': choice_value,
'display_name': force_text(choice_name, strings_only=True)
}
for choice_value, choice_name in field.choices.items()
]
return field_info
示例3: BindingDict
class BindingDict(object):
"""
This dict-like object is used to store fields on a serializer.
This ensures that whenever fields are added to the serializer we call
`field.bind()` so that the `field_name` and `parent` attributes
can be set correctly.
"""
def __init__(self, serializer):
self.serializer = serializer
self.fields = OrderedDict()
def __setitem__(self, key, field):
self.fields[key] = field
field.bind(field_name=key, parent=self.serializer)
def __getitem__(self, key):
return self.fields[key]
def __delitem__(self, key):
del self.fields[key]
def items(self):
return self.fields.items()
def keys(self):
return self.fields.keys()
def values(self):
return self.fields.values()
示例4: __init__
def __init__(self, choices, **kwargs):
# Allow either single or paired choices style:
# choices = [1, 2, 3]
# choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
pairs = [
isinstance(item, (list, tuple)) and len(item) == 2
for item in choices
]
if all(pairs):
self.choices = OrderedDict([(key, display_value) for key, display_value in choices])
else:
self.choices = OrderedDict([(item, item) for item in choices])
# Map the string representation of choices to the underlying value.
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = dict([
(six.text_type(key), key) for key in self.choices.keys()
])
super(ChoiceField, self).__init__(**kwargs)
if not self.required:
self.choices[''] = ''
self.choice_strings_to_values[''] = ''
示例5: get_field_info
def get_field_info(self, field):
field_info = super(LinkMetaData, self).get_field_info(field)
field_info = OrderedDict()
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', False)
attrs = [
'read_only', 'label', 'help_text',
'min_length', 'max_length',
'min_value', 'max_value'
]
for attr in attrs:
value = getattr(field, attr, None)
if value is not None and value != '':
field_info[attr] = force_text(value, strings_only=True)
if getattr(field, 'child', None):
field_info['child'] = self.get_field_info(field.child)
elif getattr(field, 'fields', None):
field_info['children'] = self.get_serializer_info(field)
if not field_info.get('read_only') and hasattr(field, 'choices'):
field_info['choices'] = []
for data, junk in field.choices.items():
if data and (data != 'None'):
data = ast.literal_eval(data)
field_info['choices'].append(
{
'value': data['id'],
'display_name': force_text(
data['name'],
strings_only=True)
}
)
return field_info
示例6: to_representation
def to_representation(self, instance):
"""
Overrides to nest the primary record and add sideloads.
"""
ret = OrderedDict()
base_data = self.base_serializer.__class__(
instance,
many=True,
context=self.context
).data
ret[pluralize(self.base_key)] = base_data
ret.update(self.get_sideload_objects(instance))
return ret
示例7: ChoiceField
class ChoiceField(Field):
default_error_messages = {
'invalid_choice': _('`{input}` is not a valid choice.')
}
def __init__(self, choices, **kwargs):
# Allow either single or paired choices style:
# choices = [1, 2, 3]
# choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
pairs = [
isinstance(item, (list, tuple)) and len(item) == 2
for item in choices
]
if all(pairs):
self.choices = OrderedDict([(key, display_value) for key, display_value in choices])
else:
self.choices = OrderedDict([(item, item) for item in choices])
# Map the string representation of choices to the underlying value.
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = dict([
(six.text_type(key), key) for key in self.choices.keys()
])
super(ChoiceField, self).__init__(**kwargs)
def to_internal_value(self, data):
try:
return self.choice_strings_to_values[six.text_type(data)]
except KeyError:
self.fail('invalid_choice', input=data)
def to_representation(self, value):
return self.choice_strings_to_values[six.text_type(value)]
示例8: get_field_info
def get_field_info(model):
"""
Given a model class, returns a `FieldInfo` instance containing metadata
about the various field types on the model.
"""
# Deal with the primary key.
pk = model.id if not issubclass(model, mongoengine.EmbeddedDocument) else None
# Deal with regular fields.
fields = OrderedDict()
for field_name in model._fields_ordered:
fields[field_name] = model._fields[field_name]
# Deal with forward relationships.
# Pass forward relations since there is no relations on mongodb
forward_relations = OrderedDict()
# Deal with reverse relationships.
# Pass reverse relations since there is no relations on mongodb
reverse_relations = OrderedDict()
# Shortcut that merges both regular fields and the pk,
# for simplifying regular field lookup.
fields_and_pk = OrderedDict()
fields_and_pk["pk"] = pk
fields_and_pk[getattr(pk, "name", "pk")] = pk
fields_and_pk.update(fields)
# Shortcut that merges both forward and reverse relationships
relations = OrderedDict(list(forward_relations.items()) + list(reverse_relations.items()))
return FieldInfo(pk, fields, forward_relations, reverse_relations, fields_and_pk, relations)
示例9: __init__
def __init__(self, renderer, serialized_data, serializer=None):
self.renderer = renderer
self.serialized_data = serialized_data
if serializer:
self.serializer = get_serializer(serializer)
else:
self.serializer = get_serializer(serialized_data.serializer)
self.hash = OrderedDict({"data": []})
self.included_set = set()
示例10: get_field_info
def get_field_info(self, field):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info["type"] = self.label_lookup[field]
field_info["required"] = getattr(field, "required", False)
attrs = ["read_only", "label", "help_text", "min_length", "max_length", "min_value", "max_value"]
for attr in attrs:
value = getattr(field, attr, None)
if value is not None and value != "":
field_info[attr] = force_text(value, strings_only=True)
if not field_info.get("read_only") and hasattr(field, "choices"):
field_info["choices"] = [
{"value": choice_value, "display_name": force_text(choice_name, strings_only=True)}
for choice_value, choice_name in field.choices.items()
]
return field_info
示例11: get_field_info
def get_field_info(model):
"""
Given a model class, returns a `FieldInfo` instance containing metadata
about the various field types on the model.
"""
opts = model._meta.concrete_model._meta
# Deal with the primary key.
pk = opts.pk
while pk.rel and pk.rel.parent_link:
# If model is a child via multitable inheritance, use parent's pk.
pk = pk.rel.to._meta.pk
# Deal with regular fields.
fields = OrderedDict()
for field in [field for field in opts.fields if field.serialize and not field.rel]:
fields[field.name] = field
# Deal with forward relationships.
forward_relations = OrderedDict()
for field in [field for field in opts.fields if field.serialize and field.rel]:
forward_relations[field.name] = RelationInfo(
model_field=field,
related=_resolve_model(field.rel.to),
to_many=False,
has_through_model=False
)
# Deal with forward many-to-many relationships.
for field in [field for field in opts.many_to_many if field.serialize]:
forward_relations[field.name] = RelationInfo(
model_field=field,
related=_resolve_model(field.rel.to),
to_many=True,
has_through_model=(
not field.rel.through._meta.auto_created
)
)
# Deal with reverse relationships.
reverse_relations = OrderedDict()
for relation in opts.get_all_related_objects():
accessor_name = relation.get_accessor_name()
reverse_relations[accessor_name] = RelationInfo(
model_field=None,
related=relation.model,
to_many=relation.field.rel.multiple,
has_through_model=False
)
# Deal with reverse many-to-many relationships.
for relation in opts.get_all_related_many_to_many_objects():
accessor_name = relation.get_accessor_name()
reverse_relations[accessor_name] = RelationInfo(
model_field=None,
related=relation.model,
to_many=True,
has_through_model=(
(getattr(relation.field.rel, 'through', None) is not None)
and not relation.field.rel.through._meta.auto_created
)
)
# Shortcut that merges both regular fields and the pk,
# for simplifying regular field lookup.
fields_and_pk = OrderedDict()
fields_and_pk['pk'] = pk
fields_and_pk[pk.name] = pk
fields_and_pk.update(fields)
# Shortcut that merges both forward and reverse relationships
relations = OrderedDict(
list(forward_relations.items()) +
list(reverse_relations.items())
)
return FieldInfo(pk, fields, forward_relations, reverse_relations, fields_and_pk, relations)
示例12: JsonApiAdapter
class JsonApiAdapter(object):
def __init__(self, renderer, serialized_data, serializer=None):
self.renderer = renderer
self.serialized_data = serialized_data
if serializer:
self.serializer = get_serializer(serializer)
else:
self.serializer = get_serializer(serialized_data.serializer)
self.hash = OrderedDict({"data": []})
self.included_set = set()
def serializable_hash(self):
if isinstance(self.serialized_data, list):
for obj in self.serialized_data:
result = JsonApiAdapter(self.renderer, obj,
self.serializer).serializable_hash()
self.hash["data"].append(result.get("data"))
if result.get("included"):
if "included" not in self.hash:
self.hash["included"] = []
for result in result.get("included"):
set_key = "-".join([result.get("type"),
result.get("id")])
if set_key not in self.included_set:
self.hash["included"].append(result)
self.included_set.add(set_key)
else:
self.hash["data"] = self.attributes_for_serialized_data(
self.serialized_data, self.serializer)
self.add_resource_relationships(
self.hash["data"], self.serialized_data, self.serializer)
return self.hash
def add_relationships(self, resource, rel_name, relationship):
dash_name = dasherize(rel_name)
if dash_name not in resource["relationships"]:
resource["relationships"][dash_name] = OrderedDict({
"data": []
})
if relationship.get("data"):
for data in relationship.get("data"):
try:
rel_id = data.get("id") # Serialized data
except AttributeError:
rel_id = data # Only IDs
resource["relationships"][dash_name]["data"].append(
OrderedDict([
("id", force_text(rel_id)),
("type", relationship.get("type")),
])
)
def add_relationship(self, resource, rel_name, relationship):
dash_name = dasherize(rel_name)
if dash_name not in resource["relationships"]:
resource["relationships"][dash_name] = OrderedDict({
"data": None
})
if relationship.get("data"):
try:
rel_id = relationship.get("data").get("id") # Serialized data
except AttributeError:
rel_id = relationship.get("data") # Only ID
resource["relationships"][dasherize(rel_name)]["data"] = \
OrderedDict([
("id", force_text(rel_id)),
("type", relationship.get("type")),
])
def add_included(self, rel_name, relationship, parent=None):
included_serializer = self.get_included_serializer(
relationship.get("parent_serializer"), rel_name)
if not included_serializer:
return
serialized_data = relationship.get("data")
if not isinstance(serialized_data, list):
serialized_data = [serialized_data]
included_data = []
for item in serialized_data:
if isinstance(item, six.integer_types):
# Only ID
data = self.get_included_data(
rel_name, item, included_serializer)
if data:
included_data.append(data)
resource_path = ".".join([parent, rel_name] if parent else [rel_name])
if self.include_assoc(resource_path):
if "included" not in self.hash:
self.hash["included"] = []
for data in included_data:
attrs = self.attributes_for_serialized_data(
data, included_serializer)
self.add_resource_relationships(
attrs, data, included_serializer, add_included=False)
if attrs not in self.hash.get("included"):
self.hash["included"].append(attrs)
if self.include_nested_assoc(resource_path):
for data in included_data:
relationships = self.get_relationships_data(
#.........這裏部分代碼省略.........
示例13: __init__
def __init__(self, serializer):
self.serializer = serializer
self.fields = OrderedDict()