Exemple #1
0
 def _serialize(self, value, attr, obj):
     try:
         if len(utils.get_func_args(self.func)) > 1:
             if self.parent.context is None:
                 msg = 'No context available for Function field {0!r}'.format(attr)
                 raise MarshallingError(msg)
             return self.func(obj, self.parent.context)
         else:
             return self.func(obj)
     except TypeError as te:  # Function is not callable
         raise MarshallingError(te)
     except AttributeError:  # the object is not expected to have the attribute
         pass
Exemple #2
0
 def decorated(self, *args, **kwargs):
     try:
         output = f(self, *args, **kwargs)
         if hasattr(self, 'validate') and callable(self.validate):
             if not self.validate(output):
                 msg = 'Validator {0}({1}) is not True'.format(
                     self.validate.__name__, output)
                 raise MarshallingError(getattr(self, "error", None) or msg)
         return output
     # TypeErrors should be raised if fields are not declared as instances
     except TypeError:
         raise
     except Exception as error:
         raise MarshallingError(getattr(self, "error", None) or error)
Exemple #3
0
 def __init__(self, cls_or_instance, **kwargs):
     super(List, self).__init__(**kwargs)
     if isinstance(cls_or_instance, type):
         if not issubclass(cls_or_instance, FieldABC):
             raise MarshallingError("The type of the list elements "
                                    "must be a subclass of "
                                    "marshmallow.base.FieldABC")
         self.container = cls_or_instance()
     else:
         if not isinstance(cls_or_instance, FieldABC):
             raise MarshallingError("The instances of the list "
                                    "elements must be of type "
                                    "marshmallow.base.FieldABC")
         self.container = cls_or_instance
Exemple #4
0
 def format(self, value):
     try:
         return total_seconds(value)
     except AttributeError:
         raise MarshallingError(
             '{0} cannot be formatted as a timedelta.'.format(repr(value)))
     return value
Exemple #5
0
 def _serialize(self, value, attr, obj):
     try:
         return total_seconds(value)
     except AttributeError:
         msg = '{0} cannot be formatted as a timedelta.'.format(repr(value))
         raise MarshallingError(getattr(self, 'error', None) or msg)
     return value
Exemple #6
0
 def format(self, value):
     try:
         if value is None:
             return self._format_num(self.default)
         return self._format_num(value)
     except ValueError as ve:
         raise MarshallingError(ve)
Exemple #7
0
 def format(self, value):
     try:
         return value.isoformat()
     except AttributeError:
         raise MarshallingError('{0} cannot be formatted as a date.'.format(
             repr(value)))
     return value
Exemple #8
0
 def _serialize(self, value, attr, obj):
     try:
         return value.isoformat()
     except AttributeError:
         msg = '{0} cannot be formatted as a date.'.format(repr(value))
         raise MarshallingError(getattr(self, 'error', None) or msg)
     return value
Exemple #9
0
 def format(self, value):
     try:
         if value is None:
             return text_type(utils.float_to_decimal(float(self.default)))
         return text_type(utils.float_to_decimal(float(value)))
     except ValueError as ve:
         raise MarshallingError(ve)
Exemple #10
0
 def test_can_store_field_and_field_name(self):
     field_name = 'foo'
     field = fields.Str()
     err = MarshallingError('something went wrong',
                            fields=[field],
                            field_names=[field_name])
     assert err.fields == [field]
     assert err.field_names == [field_name]
Exemple #11
0
 def format(self, value):
     try:
         ret = value.isoformat()
     except AttributeError:
         raise MarshallingError('{0} cannot be formatted as a time.'.format(
             repr(value)))
     if value.microsecond:
         return ret[:12]
     return ret
Exemple #12
0
 def _serialize(self, value, attr, obj):
     try:
         ret = value.isoformat()
     except AttributeError:
         msg = '{0!r} cannot be formatted as a time.'.format(value)
         raise MarshallingError(getattr(self, 'error', None) or msg)
     if value.microsecond:
         return ret[:12]
     return ret
Exemple #13
0
    def decorated(self, *args, **kwargs):
        if hasattr(self, 'required'):
            value = self.get_value(args[0], args[1])
            if self.required and value is None:
                raise MarshallingError('Missing data for required field.')

        try:
            output = f(self, *args, **kwargs)
            if hasattr(self, 'validate') and callable(self.validate):
                if not self.validate(output):
                    msg = 'Validator {0}({1}) is not True'.format(
                        self.validate.__name__, output)
                    raise MarshallingError(getattr(self, "error", None) or msg)
            return output
        # TypeErrors should be raised if fields are not declared as instances
        except TypeError:
            raise
        except Exception as error:
            raise MarshallingError(getattr(self, "error", None) or error)
Exemple #14
0
 def _serialize(self, value, attr, obj):
     if value:
         self.dateformat = self.dateformat or self.DEFAULT_FORMAT
         format_func = DATEFORMAT_SERIALIZATION_FUNCS.get(self.dateformat, None)
         if format_func:
             try:
                 return format_func(value, localtime=self.localtime)
             except (AttributeError, ValueError) as err:
                 raise MarshallingError(getattr(self, 'error', None) or err)
         else:
             return value.strftime(self.dateformat)
Exemple #15
0
 def _serialize(self, value, attr, obj):
     try:
         method = utils.callable_or_raise(getattr(self.parent, self.method_name, None))
         if len(utils.get_func_args(method)) > 2:
             if self.parent.context is None:
                 msg = 'No context available for Method field {0!r}'.format(attr)
                 raise MarshallingError(msg)
             return method(obj, self.parent.context)
         else:
             return method(obj)
     except AttributeError:
         pass
Exemple #16
0
 def output(self, key, obj):
     try:
         method = _callable(getattr(self.parent, self.method_name, None))
         if len(get_args(method)) > 2:
             if self.parent.context is None:
                 msg = 'No context available for Method field {0!r}'.format(
                     key)
                 raise MarshallingError(msg)
             return method(obj, self.parent.context)
         else:
             return method(obj)
     except AttributeError:
         pass
Exemple #17
0
 def output(self, key, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         raise MarshallingError(error)
Exemple #18
0
 def format(self, value):
     try:
         return text_type(value)
     except ValueError as ve:
         raise MarshallingError(self.error or ve)
Exemple #19
0
 def _serialize(self, value, attr, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         raise MarshallingError(getattr(self, 'error', None) or error)
Exemple #20
0
 def format(self, value):
     if value not in self.choices:
         raise MarshallingError(
             "{0!r} is not a valid choice for this field.".format(value))
     return value
Exemple #21
0
def raise_marshalling_value_error():
    try:
        raise ValueError('Foo bar')
    except ValueError as error:
        raise MarshallingError(error)
Exemple #22
0
 def _serialize(self, val, attr, obj):
     raise MarshallingError('oops')
Exemple #23
0
 def format(self, value):
     if value not in self.choices:
         raise MarshallingError(
             "'%s' is not a valid choice for this field." % value)
     return value
Exemple #24
0
 def format(self, value):
     dvalue = utils.float_to_decimal(float(value))
     if not dvalue.is_normal() and dvalue != ZERO:
         raise MarshallingError('Invalid Fixed precision number.')
     return text_type(
         dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN))
Exemple #25
0
def _callable(obj):
    """Checks that an object is callable, else raises a ``MarshallingError``.
    """
    if not callable(obj):
        raise MarshallingError('Object {0!r} is not callable.'.format(obj))
    return obj
Exemple #26
0
 def get_is_old(self, obj):
     try:
         return obj.age > 80
     except TypeError as te:
         raise MarshallingError(te)
Exemple #27
0
 def serialize(self, data=None):
     result = self.dump(data=data)
     if result.errors:
         raise MarshallingError(result.errors)
     return result.data