コード例 #1
0
 def _serialize(self, nested_obj, attr, obj):
     # Load up the schema first. This allows a RegistryError to be raised
     # if an invalid schema name was passed
     schema = self.schema
     if nested_obj is None:
         return None
     if self.many and utils.is_iterable_but_not_string(nested_obj):
         nested_obj = list(nested_obj)
     if not self.__updated_fields:
         schema._update_fields(obj=nested_obj, many=self.many)
         self.__updated_fields = True
     ret, errors = schema.dump(nested_obj,
                               many=self.many,
                               update_fields=not self.__updated_fields)
     if isinstance(self.only, basestring):  # self.only is a field name
         only_field = self.schema.fields[self.only]
         key = ''.join(
             [self.schema.prefix or '', only_field.dump_to or self.only])
         if self.many:
             return utils.pluck(ret, key=key)
         else:
             return ret[key]
     if errors:
         raise ValidationError(errors, data=ret)
     return ret
コード例 #2
0
 def __init__(self, default=None, attribute=None, error=None,
              validate=None, required=False, **metadata):
     self.default = default
     self.attribute = attribute
     if error:
         warnings.warn('The error parameter is deprecated. Raise a '
                       'marshmallow.ValidationError in your validators '
                       'instead.', category=DeprecationWarning)
     self.error = error
     self.validate = validate
     if utils.is_iterable_but_not_string(validate):
         if not utils.is_generator(validate):
             self.validators = validate
         else:
             self.validators = [i for i in validate()]
     elif callable(validate):
         self.validators = [validate]
     elif validate is None:
         self.validators = []
     else:
         raise ValueError("The 'validate' parameter must be a callable "
                         'or a collection of callables.')
     self.required = required
     self.metadata = metadata
     self._creation_index = Field._creation_index
     Field._creation_index += 1
     self.parent = FieldABC.parent
コード例 #3
0
    def pedido_get_list(self):
        offset = int(self.request.GET.get('start', 0))
        limit = int(self.request.GET.get('size', 10))
        sort = self.request.GET.get('sort', 'finalizacao')
        order = self.request.GET.get('order', 'asc')
        cliente = self.request.GET.get('cliente')

        pedidos = Pedido.list(self.current_user.empresa_id, offset, limit,
                              sort, order, cliente)
        total = Pedido.total(self.current_user.empresa_id, cliente)[0]
        schema = PedidoSchema(many=is_iterable_but_not_string(pedidos),
                              strict=True)
        schema.context['user'] = self.request.user

        result = schema.dump(pedidos)

        if pedidos:
            res = dumps(dict(
                data=dict(code=200, totalItems=total, pedidos=result.data)),
                        ensure_ascii=False)
            return HTTPOk(body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)),
                    ensure_ascii=False)
        return HTTPNotFound(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #4
0
ファイル: fields.py プロジェクト: praveen-p/marshmallow
    def __init__(self, default=missing_, attribute=None, load_from=None, error=None,
                 validate=None, required=False, allow_none=False, load_only=False,
                 dump_only=False, missing=missing_, **metadata):
        self.default = default
        self.attribute = attribute
        self.load_from = load_from  # this flag is used by Unmarshaller
        if error:
            warnings.warn('The error parameter is deprecated. Raise a '
                          'marshmallow.ValidationError in your validators '
                          'instead.', category=DeprecationWarning)
        self.error = error
        self.validate = validate
        if utils.is_iterable_but_not_string(validate):
            if not utils.is_generator(validate):
                self.validators = validate
            else:
                self.validators = list(validate)
        elif callable(validate):
            self.validators = [validate]
        elif validate is None:
            self.validators = []
        else:
            raise ValueError("The 'validate' parameter must be a callable "
                             "or a collection of callables.")

        self.required = required
        self.allow_none = allow_none
        self.load_only = load_only
        self.dump_only = dump_only
        self.missing = missing
        self.metadata = metadata
        self._creation_index = Field._creation_index
        Field._creation_index += 1
        self.parent = FieldABC.parent
コード例 #5
0
ファイル: schema.py プロジェクト: prtku1990/cloud_cake
    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
        """
        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)

        processed_obj = self._invoke_dump_processors(PRE_DUMP,
                                                     obj,
                                                     many,
                                                     original_data=obj)

        if update_fields:
            self._update_fields(processed_obj, many=many)

        try:
            preresult = self._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 = self._marshal.errors
            preresult = error.data
            if self.strict:
                raise error
        else:
            errors = {}
        result = self._postprocess(preresult, many, obj=obj)

        result = self._invoke_dump_processors(POST_DUMP,
                                              result,
                                              many,
                                              original_data=obj)

        return MarshalResult(result, errors)
コード例 #6
0
ファイル: schema.py プロジェクト: kakawaa/marshmallow
    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.
        """
        error_store = ErrorStore()
        errors = {}
        many = self.many if many is None else bool(many)
        if many and 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=many, original_data=obj
                )
            except ValidationError as error:
                errors = error.normalized_messages()
                result = None
        else:
            processed_obj = obj

        if not errors:
            result = self._serialize(
                processed_obj,
                fields_dict=self.fields,
                error_store=error_store,
                many=many,
                accessor=self.get_attribute,
                dict_class=self.dict_class,
                index_errors=self.opts.index_errors,
            )
            errors = error_store.errors

        if not errors and self._has_processors(POST_DUMP):
            try:
                result = self._invoke_dump_processors(
                    POST_DUMP, result, many=many, original_data=obj
                )
            except ValidationError as error:
                errors = error.normalized_messages()
        if errors:
            exc = ValidationError(errors, data=obj, valid_data=result)
            # User-defined error handler
            self.handle_error(exc, obj, many=many)
            raise exc

        return result
コード例 #7
0
    def __init__(
        self,
        default=missing_,
        attribute=None,
        load_from=None,
        dump_to=None,
        error=None,
        validate=None,
        required=False,
        allow_none=None,
        load_only=False,
        dump_only=False,
        missing=missing_,
        error_messages=None,
        **metadata
    ):
        self.default = default
        self.attribute = attribute
        self.load_from = load_from  # this flag is used by Unmarshaller
        self.dump_to = dump_to  # this flag is used by Marshaller
        self.validate = validate
        if utils.is_iterable_but_not_string(validate):
            if not utils.is_generator(validate):
                self.validators = validate
            else:
                self.validators = list(validate)
        elif callable(validate):
            self.validators = [validate]
        elif validate is None:
            self.validators = []
        else:
            raise ValueError(
                "The 'validate' parameter must be a callable "
                "or a collection of callables."
            )

        self.required = required
        # If missing=None, None should be considered valid by default
        if allow_none is None:
            if missing is None:
                self.allow_none = True
            else:
                self.allow_none = False
        else:
            self.allow_none = allow_none
        self.load_only = load_only
        self.dump_only = dump_only
        self.missing = missing
        self.metadata = metadata
        self._creation_index = Field._creation_index
        Field._creation_index += 1

        # Collect default error message from self and parent classes
        messages = {}
        for cls in reversed(self.__class__.__mro__):
            messages.update(getattr(cls, "default_error_messages", {}))
        messages.update(error_messages or {})
        self.error_messages = messages
コード例 #8
0
ファイル: fields.py プロジェクト: evgeny-sureev/marshmallow
    def __init__(self,
                 default=missing_,
                 attribute=None,
                 load_from=None,
                 error=None,
                 validate=None,
                 required=False,
                 allow_none=False,
                 load_only=False,
                 dump_only=False,
                 missing=missing_,
                 error_messages=None,
                 **metadata):
        self.default = default
        self.attribute = attribute
        self.load_from = load_from  # this flag is used by Unmarshaller
        self.validate = validate
        if utils.is_iterable_but_not_string(validate):
            if not utils.is_generator(validate):
                self.validators = validate
            else:
                self.validators = list(validate)
        elif callable(validate):
            self.validators = [validate]
        elif validate is None:
            self.validators = []
        else:
            raise ValueError("The 'validate' parameter must be a callable "
                             "or a collection of callables.")

        if isinstance(required, basestring):
            warnings.warn(
                'Passing a string for `required` is deprecated. Pass '
                '{"required": "Your message"} to `error_messages` instead.',
                DeprecationWarning)
        self.required = required
        if isinstance(allow_none, basestring):
            warnings.warn(
                'Passing a string for `allow_none` is deprecated. Pass '
                '{"null": "Your message"} to `error_messages` instead.',
                DeprecationWarning)
        self.allow_none = allow_none
        self.load_only = load_only
        self.dump_only = dump_only
        self.missing = missing
        self.metadata = metadata
        self._creation_index = Field._creation_index
        Field._creation_index += 1
        self.parent = FieldABC.parent

        # Collect default error message from self and parent classes
        messages = {}
        for cls in reversed(self.__class__.__mro__):
            messages.update(getattr(cls, 'default_error_messages', {}))
        messages.update(error_messages or {})
        self.error_messages = messages
コード例 #9
0
ファイル: schema.py プロジェクト: exuusdevteam/asprin
    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
        """
        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)

        processed_obj = self._invoke_dump_processors(PRE_DUMP, obj, many, original_data=obj)

        if update_fields:
            self._update_fields(processed_obj, many=many)

        try:
            preresult = self._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 = self._marshal.errors
            preresult = error.data
            if self.strict:
                raise error
        else:
            errors = {}
        result = self._postprocess(preresult, many, obj=obj)

        result = self._invoke_dump_processors(POST_DUMP, result, many, original_data=obj)

        return MarshalResult(result, errors)
コード例 #10
0
 def build_validator_list(src):
     if src is None:
         return []
     if utils.is_iterable_but_not_string(src):
         if utils.is_generator(src):
             return list(src)
         else:
             return src
     elif callable(src):
         return [src]
     else:
         raise ValueError("The 'validate' parameter must be a callable "
                          "or a collection of callables.")
コード例 #11
0
ファイル: fields.py プロジェクト: ak795/HCKERTH
    def __init__(self, default=missing_, attribute=None, load_from=None, dump_to=None,
                 error=None, validate=None, required=False, allow_none=None, load_only=False,
                 dump_only=False, missing=missing_, error_messages=None, **metadata):
        self.default = default
        self.attribute = attribute
        self.load_from = load_from  # this flag is used by Unmarshaller
        self.dump_to = dump_to  # this flag is used by Marshaller
        self.validate = validate
        if utils.is_iterable_but_not_string(validate):
            if not utils.is_generator(validate):
                self.validators = validate
            else:
                self.validators = list(validate)
        elif callable(validate):
            self.validators = [validate]
        elif validate is None:
            self.validators = []
        else:
            raise ValueError("The 'validate' parameter must be a callable "
                             "or a collection of callables.")

        self.required = required
        # If missing=None, None should be considered valid by default
        if allow_none is None:
            if missing is None:
                self.allow_none = True
            else:
                self.allow_none = False
        else:
            self.allow_none = allow_none
        self.load_only = load_only
        self.dump_only = dump_only
        self.missing = missing
        self.metadata = metadata
        self._creation_index = Field._creation_index
        Field._creation_index += 1
        self.parent = FieldABC.parent

        # Collect default error message from self and parent classes
        messages = {}
        for cls in reversed(self.__class__.__mro__):
            messages.update(getattr(cls, 'default_error_messages', {}))
        messages.update(error_messages or {})
        self.error_messages = messages
コード例 #12
0
    def tamanho_get_list(self):
        tamanhos = Tamanho.list(self.current_user.empresa_id)
        total = Tamanho.total(self.current_user.empresa_id)[0]
        schema = TamanhoSchema(many=is_iterable_but_not_string(tamanhos),
                               strict=True)
        result = schema.dump(tamanhos)

        if tamanhos:
            res = dumps(dict(
                data=dict(code=200, totalItems=total, tamanhos=result.data)),
                        ensure_ascii=False)
            return HTTPOk(body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)),
                    ensure_ascii=False)
        return HTTPNotFound(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #13
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def endereco_get_list(self):
        cliente_hash_id = self.request.matchdict.get('cliHashid')
        cliente_id = get_decoded_id('clientes', cliente_hash_id, self.current_user.empresa_id)

        enderecos = Endereco.list(cliente_id)
        schema = EnderecoSchema(many=is_iterable_but_not_string(enderecos), strict=True)
        result = schema.dump(enderecos)

        if enderecos:
            res = dumps(dict(
                data=dict(
                    code=200,
                    enderecos=result.data)),
                ensure_ascii=False)
            return HTTPOk(body=res, content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)), ensure_ascii=False)
        return HTTPNotFound(body=res, content_type='application/json; charset=UTF-8')
コード例 #14
0
    def adicional_get_list(self):
        adicionais = Adicional.list(self.current_user.empresa_id)
        total = Adicional.total(self.current_user.empresa_id)[0]
        schema = AdicionalSchema(many=is_iterable_but_not_string(adicionais),
                                 strict=True)
        schema.context['user'] = self.request.user
        result = schema.dump(adicionais)

        if adicionais:
            res = dumps(dict(
                data=dict(code=200, totalItems=total, adicionais=result.data)),
                        ensure_ascii=False)
            return HTTPOk(body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)),
                    ensure_ascii=False)
        return HTTPNotFound(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #15
0
    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.
        .. versionchanged:: 3.0.0rc9
            Validation no longer occurs upon serialization.
        """
        many = self.many if many is None else bool(many)
        if many and is_iterable_but_not_string(obj):
            obj = list(obj)

        if self._has_processors(PRE_DUMP):
            processed_obj = self._invoke_dump_processors(PRE_DUMP,
                                                         obj,
                                                         many=many,
                                                         original_data=obj)
        else:
            processed_obj = obj

        result = self._serialize(processed_obj, many=many)

        if self._has_processors(POST_DUMP):
            result = self._invoke_dump_processors(POST_DUMP,
                                                  result,
                                                  many=many,
                                                  original_data=obj)

        return result
コード例 #16
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def cliente_get_list(self):
        offset = int(self.request.GET.get('start', 0))
        limit = int(self.request.GET.get('size', 10))
        sort = self.request.GET.get('sort', 'nome')
        order = self.request.GET.get('order', 'asc')
        nome = self.request.GET.get('nome')
        telefone = self.request.GET.get('telefone')
        ativo = self.request.GET.get('ativo')
        q = self.request.GET.get('q', 'list')

        # 'q' define retorno de lista completa ou tipo select (valor/label)
        if q == 'select' and (nome or telefone):
            clientes = Cliente.select_list(self.current_user.empresa_id, limit,
                                           nome, telefone)
            total = len(clientes)
            schema = ClienteSelectSchema(many=True, strict=True)
        else:
            clientes = Cliente.list(self.current_user.empresa_id, offset,
                                    limit, sort, order, nome, ativo)
            total = Cliente.total(self.current_user.empresa_id, nome, ativo)[0]
            schema = ClienteSchema(many=is_iterable_but_not_string(clientes),
                                   strict=True)

        result = schema.dump(clientes)

        if clientes:
            res = dumps(dict(
                data=dict(code=200, totalItems=total, clientes=result.data)),
                        ensure_ascii=False)
            return HTTPOk(body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)),
                    ensure_ascii=False)
        return HTTPNotFound(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #17
0
ファイル: fields.py プロジェクト: ricoputrap/API-Todo-App
def ensure_list(value):
    return value if is_iterable_but_not_string(value) else [value]
コード例 #18
0
ファイル: schema.py プロジェクト: kaya-zekioglu/marshmallow
    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
コード例 #19
0
    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
        """
        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:
            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 = self._marshal(processed_obj,
                                          self.fields,
                                          many=many,
                                          accessor=self.get_attribute,
                                          dict_class=self.dict_class,
                                          index_errors=self.opts.index_errors,
                                          **kwargs)
            except ValidationError as error:
                errors = self._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:
            exc = ValidationError(errors,
                                  field_names=self._marshal.error_field_names,
                                  fields=self._marshal.error_fields,
                                  data=obj,
                                  **self._marshal.error_kwargs)
            self.handle_error(exc, obj)
            if self.strict:
                raise exc

        return MarshalResult(result, errors)
コード例 #20
0
ファイル: fields.py プロジェクト: RaminFP/PYHelper
def ensure_list(value):
    return value if is_iterable_but_not_string(value) else [value]
コード例 #21
0
    async def async_dump(self, obj, many=None, update_fields=True, **kwargs):
        # Callable marshalling object
        marshal = 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:
            try:
                processed_obj = await self._async_invoke_dump_processors(
                    ASYNC_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 = await self._async_invoke_dump_processors(
                    ASYNC_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)