Exemplo n.º 1
0
    def __call__(self, field, value):
        result = self.function(value)

        if not result:
            raise Invalid(self.message, field)

        if isinstance(result, string_types):
            raise Invalid(result, field)
Exemplo n.º 2
0
    def validate(self, value):
        """ validate value """
        if self.required and (value == self.missing or value is null):
            raise Invalid(self.error_required, self)

        if self.typ is not None and not isinstance(value, self.typ):
            raise Invalid(self.error_wrong_type, self)

        if self.validator is not None:
            self.validator(self, value)
Exemplo n.º 3
0
    def __call__(self, field, value):
        if self.min is not None:
            if len(value) < self.min:
                min_err = _('Shorter than minimum length ${min}',
                            mapping={'min': self.min})
                raise Invalid(min_err, field)

        if self.max is not None:
            if len(value) > self.max:
                max_err = _('Longer than maximum length ${max}',
                            mapping={'max': self.max})
                raise Invalid(max_err, field)
Exemplo n.º 4
0
    def add_field_error(self, name, err):
        """
        Add error to specific field. Set error `field` to specified field.
        """
        if isinstance(err, string_types):
            err = Invalid(err)

        field = self.fieldset[name]

        err.field = field
        if field.error is None:
            field.error = err

        self.append(err)
Exemplo n.º 5
0
    def add_field_error(self, name, err):
        """
        Add error to specific field. Set error `field` to specified field.
        """
        if isinstance(err, string_types):
            err = Invalid(err)

        field = self.fieldset[name]

        err.field = field
        if field.error is None:
            field.error = err

        self.append(err)
Exemplo n.º 6
0
    def to_field(self, value):
        if not value:
            return null

        try:
            return list(filter(None, [s.strip() for s in value.split('\n')]))
        except Exception:
            raise Invalid(self.error_msg, self, {'val': value})
Exemplo n.º 7
0
    def to_field(self, value):
        if not value:
            return null

        try:
            return self.typ(value)
        except Exception:
            raise Invalid(self.error_msg, self, mapping={'val': value})
Exemplo n.º 8
0
    def to_field(self, value):
        if not value:
            return null

        try:
            return self.vocabulary.get_term_bytoken(value).value
        except LookupError:
            raise Invalid(self.error_msg, self, {'val': value})
Exemplo n.º 9
0
 def deserialize(self, value):
     if not value:
         return null
     try:
         return datetime.datetime.strptime(value, '%m/%d/%Y').date()
     except Exception as e:
         raise Invalid(
             self, _('Invalid date', mapping={'val': value, 'err': e}))
Exemplo n.º 10
0
 def __call__(self, field, value):
     if not value in self.choices:
         choices = ', '.join(['%s' % x for x in self.choices])
         err = _('"${val}" is not one of ${choices}',
                 mapping={
                     'val': value,
                     'choices': choices
                 })
         raise Invalid(field, err)
Exemplo n.º 11
0
 def to_form(self, value):
     val = value
     try:
         res = []
         for val in value:
             res.append(self.vocabulary.get_term(val).token)
         return res
     except:
         raise Invalid(self.error_msg, self, {'val': val})
Exemplo n.º 12
0
    def __call__(self, field, value):
        if self.min is not None:
            if value < self.min:
                min_err = _(self.min_err,
                            mapping={
                                'val': value,
                                'min': self.min
                            })
                raise Invalid(min_err, field)

        if self.max is not None:
            if value > self.max:
                max_err = _(self.max_err,
                            mapping={
                                'val': value,
                                'max': self.max
                            })
                raise Invalid(max_err, field)
Exemplo n.º 13
0
    def deserialize(self, value):
        if value != 0 and not value:
            return null

        try:
            return self.num(value)
        except Exception:
            raise Invalid(
                self, _('"${val}" is not a number', mapping={'val': value}))
Exemplo n.º 14
0
    def __call__(self, field, value):
        msgs = []
        for validator in self.validators:
            try:
                validator(field, value)
            except Invalid as e:
                msgs.append(str(e))

        if msgs:
            raise Invalid(msgs, field)
Exemplo n.º 15
0
    def deserialize(self, value):
        if not value:
            return null

        try:
            return self.vocabulary.get_term_bytoken(value).value
        except Exception:
            raise Invalid(
                self, _('"${val}" is not in vocabulary',
                        mapping={'val': value}))
Exemplo n.º 16
0
    def validate(self, value):
        if value is null and self.form_value:
            value = self.form_value

        super(FileField, self).validate(value)

        if value is null:
            return

        if self.max_size:
            value['fp'].seek(0, 2)
            size = value['fp'].tell()
            value['fp'].seek(0)

            if size > self.max_size:
                raise Invalid(self.error_max_size, self)

        if self.allowed_types and value['mimetype'] not in self.allowed_types:
            raise Invalid(self.error_unknown_type, self)
Exemplo n.º 17
0
    def serialize(self, value):
        if value is null:
            return null

        try:
            return self.vocabulary.get_term(value).token
        except Exception:
            raise Invalid(
                self, _('"${val}" is not in vocabulary',
                        mapping={'val': value}))
Exemplo n.º 18
0
    def deserialize(self, value):
        if not value:
            return null

        try:
            return [s.strip() for s in value.split()]
        except Exception:
            raise Invalid(self,
                          _('"${val}" is not a list',
                            mapping={'val': value}),
                          )
Exemplo n.º 19
0
    def to_form(self, value):
        if value is null:
            return null

        if isinstance(value, datetime.datetime):
            value = value.date()

        if not isinstance(value, datetime.date):
            raise Invalid(self.error_msg, self, {'val': value})

        return value.isoformat()
Exemplo n.º 20
0
    def serialize(self, value):
        if value is null or not value:
            return null

        try:
            return '\n'.join(value)
        except Exception:
            raise Invalid(self,
                          _('"${val}" is not a list',
                            mapping={'val': value}),
                          )
Exemplo n.º 21
0
    def serialize(self, value):
        if value is null:
            return null

        try:
            return str(self.num(value))
        except Exception:
            raise Invalid(self,
                          _('"${val}" is not a number',
                            mapping={'val': value}),
                          )
Exemplo n.º 22
0
    def to_field(self, value):
        if not value:
            return null

        val = value
        try:
            res = []
            for val in value:
                res.append(self.vocabulary.get_term_bytoken(val).value)
            return res
        except:
            raise Invalid(self.error_msg, self, {'val': val})
Exemplo n.º 23
0
 def serialize(self, value):
     if value is null:
         return null
     try:
         res = []
         for val in value:
             res.append(self.vocabulary.get_term(val).token)
         return res
     except (LookupError, TypeError):
         raise Invalid(
             self, _('"${val}" is not in vocabulary',
                     mapping={'val': value}))
Exemplo n.º 24
0
    def serialize(self, value):
        if value is null:
            return null

        if isinstance(value, datetime.datetime):
            value = value.date()

        if not isinstance(value, datetime.date):
            raise Invalid(self,
                          _('"${val}" is not a date object',
                            mapping={'val': value}))

        return value.isoformat()
Exemplo n.º 25
0
    def serialize(self, value):
        if value is null or value is None:
            return null

        if isinstance(value, datetime.datetime):
            value = value.date()

        if not isinstance(value, datetime.date):
            raise Invalid(self,
                          _('"${val}" is not a date object',
                            mapping={'val': value}))

        return value.strftime('%m/%d/%Y')
Exemplo n.º 26
0
    def to_form(self, value):
        if value is null or value is None or not value:
            return null

        if type(value) is datetime.date:  # cannot use isinstance; dt subs date
            value = datetime.datetime.combine(value, datetime.time())

        if not isinstance(value, datetime.datetime):
            raise Invalid(self.error_msg, self, {'val': value})

        if value.tzinfo is None:
            value = value.replace(tzinfo=self.default_tzinfo)

        return value.strftime('%Y-%m-%d %H:%M')
Exemplo n.º 27
0
    def to_field(self, value):
        if value is null or not value:
            return null

        try:
            v = str(value).lower()
            if v.startswith('gmt'):
                v = 'etc/%s' % v
            try:
                return pytz.timezone(v)
            except:
                return pytz.timezone(self._tzs[v])
        except:
            raise Invalid(self.error_msg, self, {'val': value})
Exemplo n.º 28
0
    def deserialize(self, value):
        if value is null or not value:
            return null

        try:
            v = str(value).lower()
            if v.startswith('gmt'):
                v = 'etc/%s' % v
            try:
                return pytz.timezone(v)
            except:
                return pytz.timezone(self._tzs[v])
        except:
            raise Invalid(self,
                _('"${val}" is not a timezone', mapping={'val': value}))
Exemplo n.º 29
0
    def to_field(self, value):
        if not value:
            return null

        try:
            result = iso8601.parse_date(value)
            result = result.date()
        except (iso8601.ParseError, TypeError):
            try:
                year, month, day = map(int, value.split('-', 2))
                result = datetime.date(year, month, day)
            except Exception:
                raise Invalid(self.error_invalid_date, self)

        return result
Exemplo n.º 30
0
    def serialize(self, value):
        if value is null or value is None or not value:
            return null

        if type(value) is datetime.date:  # cannot use isinstance; dt subs date
            value = datetime.datetime.combine(value, datetime.time())

        if not isinstance(value, datetime.datetime):
            raise Invalid(
                self, _('"${val}" is not a datetime object',
                        mapping={'val': value}))

        if value.tzinfo is None:
            value = value.replace(tzinfo=self.default_tzinfo)

        return value.isoformat()
Exemplo n.º 31
0
    def deserialize(self, value):
        if not value:
            return null

        try:
            result = iso8601.parse_date(
                value, default_timezone=self.default_tzinfo)
        except (iso8601.ParseError, TypeError) as e:
            try:
                year, month, day = map(int, value.split('-', 2))
                result = datetime.datetime(year, month, day,
                                           tzinfo=self.default_tzinfo)
            except Exception as e:
                raise Invalid(self, _('Invalid date',
                                      mapping={'val': value, 'err': e}))
        return result