def __init__(self, only=(), exclude=(), prefix='', strict=None, many=False, context=None, load_only=(), dump_only=(), partial=False): # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) self.many = many self.only = only self.exclude = exclude self.prefix = prefix self.strict = strict if strict is not None else self.opts.strict self.ordered = self.opts.ordered self.load_only = set(load_only) or set(self.opts.load_only) self.dump_only = set(dump_only) or set(self.opts.dump_only) self.partial = partial #: Dictionary mapping field_names -> :class:`Field` objects self.fields = self.dict_class() #: Callable marshalling object self._marshal = marshalling.Marshaller(prefix=self.prefix) #: Callable unmarshalling object self._unmarshal = marshalling.Unmarshaller() self.context = context or {} self._normalize_nested_options() self._types_seen = set() self._update_fields(many=many)
def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None, many=False, context=None, load_only=(), dump_only=(), partial=False): # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) self.many = many self.only = only self.exclude = exclude self.prefix = prefix self.strict = strict if strict is not None else self.opts.strict self.ordered = self.opts.ordered self.load_only = set(load_only) or set(self.opts.load_only) self.dump_only = set(dump_only) or set(self.opts.dump_only) self.partial = partial #: Dictionary mapping field_names -> :class:`Field` objects self.fields = self.dict_class() #: Callable marshalling object self._marshal = marshalling.Marshaller( prefix=self.prefix ) #: Callable unmarshalling object self._unmarshal = marshalling.Unmarshaller() if extra: warnings.warn( 'The `extra` argument is deprecated. Use a post_dump ' 'method to add additional data instead.', DeprecationWarning ) self.extra = extra self.context = context or {} self._normalize_nested_options() self._types_seen = set() self._update_fields(many=many)
def __init__(self, extra=None, only=(), exclude=(), prefix='', strict=False, many=False, skip_missing=False, context=None): # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) self.many = many self.opts = self.OPTIONS_CLASS(self.Meta) self.only = only self.exclude = exclude self.prefix = prefix self.strict = strict or self.opts.strict self.skip_missing = skip_missing or self.opts.skip_missing self.ordered = self.opts.ordered #: Dictionary mapping field_names -> :class:`Field` objects self.fields = self.dict_class() #: Callable marshalling object self._marshal = marshalling.Marshaller(prefix=self.prefix) #: Callable unmarshalling object self._unmarshal = marshalling.Unmarshaller() self.extra = extra self.context = context or {} self._update_fields(many=many)
def dump(self, obj, many=None): # noqa:C901 marshaller = marshalling.Marshaller() errors = {} many = self.many if many is None else bool(many) processed_obj = obj result = None if self._has_processors(PRE_DUMP): try: processed_obj = self._invoke_dump_processors( PRE_DUMP, obj, many, original_data=obj, ) except ValidationError as error: errors = error.normalized_messages() if not errors: try: result = marshaller.serialize( processed_obj, self._fields, many=False, accessor=self.get_attribute, dict_class=self.dict_class, index_errors=self.opts.index_errors, ) except ValidationError as error: errors = marshaller.errors result = error.data if not errors and self._has_processors(POST_DUMP): try: result = self._invoke_dump_processors( POST_DUMP, result, many, original_data=obj, ) except ValidationError as error: errors = error.normalized_messages() if errors: error_field_names = getattr(marshaller, 'error_field_names', []) exc = ValidationError( errors, field_names=error_field_names, data=obj, valid_data=result, **marshaller.error_kwargs ) # User-defined error handler self.handle_error(exc, obj) raise exc return result
def __init__(self, extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=()): # copy declared fields from metaclass self.declared_fields = copy.deepcopy(self._declared_fields) self.many = many self.only = only self.exclude = exclude self.prefix = prefix self.strict = strict or self.opts.strict self.ordered = self.opts.ordered self.load_only = set(load_only) or set(self.opts.load_only) self.dump_only = set(dump_only) or set(self.opts.dump_only) #: Dictionary mapping field_names -> :class:`Field` objects self.fields = self.dict_class() #: Callable marshalling object self._marshal = marshalling.Marshaller(prefix=self.prefix) #: Callable unmarshalling object self._unmarshal = marshalling.Unmarshaller() self.extra = extra self.context = context or {} self._update_fields(many=many) # Accessor function takes schema as first argument self._accessor = partial(self.opts.accessor, self) if self.opts.accessor else None # Error handler also takes schema as first argument if self.opts.error_handler: self._error_handler = partial(self.opts.error_handler, self) else: self._error_handler = None
def dump(self, obj, many=None, update_fields=True): """Serialize an object to native Python data types according to this Schema's fields. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :param bool update_fields: Whether to update the schema's field classes. Typically set to `True`, but may be `False` when serializing a homogenous collection. This parameter is used by `fields.Nested` to avoid multiple updates. :return: A dict of serialized data :rtype: dict .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0b7 This method returns the serialized data rather than a ``(data, errors)`` duple. A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised if ``obj`` is invalid. """ # Callable marshalling object marshal = marshalling.Marshaller(prefix=self.prefix) errors = {} many = self.many if many is None else bool(many) if many and utils.is_iterable_but_not_string(obj): obj = list(obj) if self._has_processors(PRE_DUMP): try: processed_obj = self._invoke_dump_processors( PRE_DUMP, obj, many, original_data=obj, ) except ValidationError as error: errors = error.normalized_messages() result = None else: processed_obj = obj if not errors: if update_fields: obj_type = type(processed_obj) if obj_type not in self._types_seen: self._update_fields(processed_obj, many=many) if not isinstance(processed_obj, Mapping): self._types_seen.add(obj_type) try: result = marshal( processed_obj, self.fields, many=many, accessor=self.get_attribute, dict_class=self.dict_class, index_errors=self.opts.index_errors, ) except ValidationError as error: errors = marshal.errors result = error.data if not errors and self._has_processors(POST_DUMP): try: result = self._invoke_dump_processors( POST_DUMP, result, many, original_data=obj, ) except ValidationError as error: errors = error.normalized_messages() if errors: exc = ValidationError(errors, field_names=marshal.error_field_names, data=obj, valid_data=result, **marshal.error_kwargs) # User-defined error handler self.handle_error(exc, obj) raise exc return result
def dump(self, obj, many=None, update_fields=True, **kwargs): """Serialize an object to native Python data types according to this Schema's fields. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :param bool update_fields: Whether to update the schema's field classes. Typically set to `True`, but may be `False` when serializing a homogenous collection. This parameter is used by `fields.Nested` to avoid multiple updates. :return: A tuple of the form (``data``, ``errors``) :rtype: `MarshalResult`, a `collections.namedtuple` .. versionadded:: 1.0.0 """ # Callable marshalling object marshal = marshalling.Marshaller(prefix=self.prefix) errors = {} many = self.many if many is None else bool(many) if not many and utils.is_collection(obj) and not utils.is_keyed_tuple(obj): warnings.warn('Implicit collection handling is deprecated. Set ' 'many=True to serialize a collection.', category=DeprecationWarning) if many and utils.is_iterable_but_not_string(obj): obj = list(obj) if self._has_processors: try: processed_obj = self._invoke_dump_processors( PRE_DUMP, obj, many, original_data=obj) except ValidationError as error: errors = error.normalized_messages() result = None else: processed_obj = obj if not errors: if update_fields: obj_type = type(processed_obj) if obj_type not in self._types_seen: self._update_fields(processed_obj, many=many) if not isinstance(processed_obj, Mapping): self._types_seen.add(obj_type) try: preresult = marshal( processed_obj, self.fields, many=many, # TODO: Remove self.__accessor__ in a later release accessor=self.get_attribute or self.__accessor__, dict_class=self.dict_class, index_errors=self.opts.index_errors, **kwargs ) except ValidationError as error: errors = marshal.errors preresult = error.data result = self._postprocess(preresult, many, obj=obj) if not errors and self._has_processors: try: result = self._invoke_dump_processors( POST_DUMP, result, many, original_data=obj) except ValidationError as error: errors = error.normalized_messages() if errors: # TODO: Remove self.__error_handler__ in a later release if self.__error_handler__ and callable(self.__error_handler__): self.__error_handler__(errors, obj) exc = ValidationError( errors, field_names=marshal.error_field_names, fields=marshal.error_fields, data=obj, **marshal.error_kwargs ) self.handle_error(exc, obj) if self.strict: raise exc return MarshalResult(result, errors)
def dump(self, obj, many=None): """Serialize an object to native Python data types according to this Schema's fields. :param obj: The object to serialize. :param bool many: Whether to serialize `obj` as a collection. If `None`, the value for `self.many` is used. :return: A dict of serialized data :rtype: dict .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0b7 This method returns the serialized data rather than a ``(data, errors)`` duple. A :exc:`ValidationError <marshmallow.exceptions.ValidationError>` is raised if ``obj`` is invalid. """ # Callable marshalling object marshal = marshalling.Marshaller() errors = {} many = self.many if many is None else bool(many) if many and utils.is_iterable_but_not_string(obj): obj = list(obj) if self._has_processors(PRE_DUMP): try: processed_obj = self._invoke_dump_processors( PRE_DUMP, obj, many, original_data=obj, ) except ValidationError as error: errors = error.normalized_messages() result = None else: processed_obj = obj if not errors: result = marshal( processed_obj, self.fields, many=many, accessor=self.get_attribute, dict_class=self.dict_class, index_errors=self.opts.index_errors, ) errors = marshal.errors if not errors and self._has_processors(POST_DUMP): try: result = self._invoke_dump_processors( POST_DUMP, result, many, original_data=obj, ) except ValidationError as error: errors = error.normalized_messages() if errors: exc = ValidationError( errors, data=obj, valid_data=result, **marshal.error_kwargs ) # User-defined error handler self.handle_error(exc, obj) raise exc return result