def fields_for_model(self, model): result = OrderedDict() for field in model._meta.sorted_fields: ma_field = self.convert_field(field) if ma_field: result[field.name] = ma_field return result
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)
def __get_fields_to_marshal(self, all_fields): '''Filter all_fields based on self.only and self.exclude.''' # Default 'only' to all the nested fields ret = OrderedDict() if all_fields is None: return ret elif isinstance(self.only, basestring): ret[self.only] = all_fields[self.only] return ret else: only = set(all_fields) if self.only is None else set(self.only) if self.exclude and self.only: # Make sure that only takes precedence exclude = set(self.exclude) - only else: exclude = set([]) if self.exclude is None else set(self.exclude) filtered = ((k, v) for k, v in all_fields.items() if k in only and k not in exclude) return OrderedDict(filtered)
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)
def fields_for_model(self, model): fields = self.opts.fields exclude = self.opts.exclude result = OrderedDict() for field in model._meta.sorted_fields: if fields and field.name not in fields: continue if exclude and field.name in exclude: continue for field in [ f for f in model._meta.sorted_fields if not fields or f.name in fields ]: ma_field = self.convert_field(field) if ma_field: result[field.name] = ma_field return result
def __init__(self, obj=None, extra=None, only=None, exclude=None, prefix='', strict=False, many=False, context=None): if not many and utils.is_collection(obj): warnings.warn( 'Implicit collection handling is deprecated. Set ' 'many=True to serialize a collection.', category=DeprecationWarning) # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) self.fields = OrderedDict() self.__data = None self.obj = obj self.many = many self.opts = self.OPTIONS_CLASS(self.Meta) self.only = only or () self.exclude = exclude or () self.prefix = prefix self.strict = strict or self.opts.strict #: Callable marshalling object self.marshal = fields.Marshaller(prefix=self.prefix, strict=self.strict) self.extra = extra self.context = context if isinstance(obj, types.GeneratorType): self.obj = list(obj) else: self.obj = obj self._update_fields(obj) # If object is passed in, marshal it immediately so that errors are stored if self.obj is not None: raw_data = self.marshal(self.obj, self.fields, many=self.many) if self.extra: raw_data.update(self.extra) self.__data = self.process_data(raw_data)
def __filter_fields(self, field_names): """Return only those field_name:field_obj pairs specified by ``field_names``. :param set field_names: Field names to include in the final return dictionary. :returns: An OrderedDict of field_name:field_obj pairs. """ # Convert obj to a dict obj_marshallable = utils.to_marshallable_type(self.obj, field_names=field_names) if obj_marshallable and self.many: try: # Homogeneous collection obj_prototype = obj_marshallable[0] except IndexError: # Nothing to serialize return self.declared_fields obj_dict = utils.to_marshallable_type(obj_prototype, field_names=field_names) else: obj_dict = obj_marshallable ret = OrderedDict() for key in field_names: if key in self.declared_fields: ret[key] = self.declared_fields[key] else: if obj_dict: try: attribute_type = type(obj_dict[key]) except KeyError: raise AttributeError( '"{0}" is not a valid field for {1}.'.format( key, self.obj)) field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)() else: # Object is None field_obj = fields.Field() # map key -> field (default to Raw) ret[key] = field_obj return ret
class Meta: include = OrderedDict([('from', fields.Str()), ('in', fields.Str()), ('@at', fields.Str())]) ordered = True
'github_button': False, 'gratipay_user': '******', 'code_font_size': '0.85em', 'warn_bg': '#FFC', 'warn_border': '#EEE', # Used to populate the useful-links.html template 'extra_nav_links': OrderedDict([ ('marshmallow-sqlalchemy @ PyPI', 'http://pypi.python.org/pypi/marshmallow-sqlalchemy'), ('marshmallow-sqlalchemy @ GitHub', 'http://github.com/marshmallow-code/marshmallow-sqlalchemy'), ('Issue Tracker', 'http://github.com/marshmallow-code/marshmallow-sqlalchemy/issues'), ]) } html_sidebars = { 'index': [ 'about.html', 'useful-links.html', 'searchbox.html', 'donate.html', ], '**': [ 'about.html', 'useful-links.html', 'localtoc.html', 'relations.html', 'searchbox.html', 'donate.html'
def test_dict_field_serialize_ordereddict(self, user): user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) field = fields.Dict() assert field.serialize('various_data', user) == \ OrderedDict([("foo", "bar"), ("bar", "baz")])