Example #1
0
    def deserialize(self, node, cstruct):
        if not cstruct:
            return colander.null
        bindings = node.bindings or {}
        request = bindings.get('request', None)
        if not request:
            raise RuntimeError('"request" has not found inside of schema node bindings')

        if not isinstance(cstruct, str):
            raise colander.Invalid(
                node,
                colander._(
                    '${val} is not a string with URL',
                    mapping={'val': cstruct},
                ),
            )
        try:
            resource_path = urlsplit(cstruct).path
        except ValueError as e:
            raise colander.Invalid(
                node,
                colander._(
                    '${val} is not a valid URL: ${err}',
                    mapping={'val': cstruct, 'err': e},
                ),
            )
        try:
            resource = find_resource(request.root, resource_path)
        except KeyError:
            raise colander.Invalid(node, colander._('Resource has not found'))
        return resource
Example #2
0
 def translate_error(node, value):
     min_err = _(_('${val} is less than minimum value ${min}'),
                 mapping={
                     'val': 'value',
                     'min': 'min'
                 })
     raise Invalid(node, min_err)
Example #3
0
    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        try:
            result = json.dumps(appstruct)
        except Exception as e:
            raise colander.Invalid(
                node,
                colander._(
                    '${val} cannot be JSON-serialized: ${err}',
                    mapping={
                        'val': appstruct,
                        'err': e
                    },
                ),
            )

        if not result.startswith('{'):
            raise colander.Invalid(
                node,
                colander._('${val} does not serialize to a JSON object',
                           mapping={'val': appstruct}))

        return result
Example #4
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if not isinstance(cstruct, compat.string_types):
            raise Invalid(node, _("must be a string"))

        return self.decoder(cstruct)
Example #5
0
    def serialize(self, node, appstruct):
        if appstruct is null:
            return null

        if not isinstance(appstruct, str):
            raise Invalid(node, _("must be a byte string"))

        return self.encoder(appstruct)
Example #6
0
    def deserialize(self, node, cstruct):
        if cstruct != 0 and not cstruct:
            return null

        try:
            return self.num(cstruct)
        except Exception:
            raise Invalid(node, _('"${val}" is not a number', mapping={'val': cstruct}))
Example #7
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        try:
            return IPAddress(cstruct, version=self._version)
        except:
            raise Invalid(node, _("must be a string representation of an IP address"))
Example #8
0
    def serialize(self, node, appstruct):
        if appstruct in null:
            return null

        try:
            return self.num(appstruct)
        except Exception:
            raise Invalid(node, _('"${val}" is not a number', mapping={'val': appstruct}))
Example #9
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if isinstance(cstruct, basestring):
            return cstruct

        raise Invalid(node, _('${val} is not a string', mapping={'val': cstruct}))
Example #10
0
    def deserialize(self, node, cstruct):
        if cstruct != 0 and not cstruct:
            return null

        try:
            return self.num(cstruct)
        except Exception:
            raise Invalid(
                node, _('"${val}" is not a number', mapping={'val': cstruct}))
Example #11
0
 def __call__(self, node, value):
     if not any(v(value) for v in self._validators):
         choices = ', '.join(x.__name__ for x in self.interfaces)
         err = colander._('Type of "${val}" is not one of ${choices}',
                          mapping={
                              'val': value,
                              'choices': choices
                          })
         raise colander.Invalid(node, err)
Example #12
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if isinstance(cstruct, compat.string_types):
            return cstruct

        raise Invalid(node,
                      _('${val} is not a string', mapping={'val': cstruct}))
Example #13
0
 def deserialize(self, node, cstruct):
     value = super(Choice, self).deserialize(node, cstruct)
     try:
         choice = self.choice_class(value)
     except self.choice_class.IsInvalidChoice:
         choices = ', '.join(['%s' % x for x in self.choice_class.choices])
         err = colander._('"${val}" is not one of ${choices}',
                 mapping={'val':value, 'choices':choices})
         raise colander.Invalid(node, err)
     return choice
Example #14
0
    def serialize(self, node, appstruct):
        if not appstruct:
            return self.default

        if not isinstance(appstruct, datetime.datetime):
            raise colander.Invalid(node,
                          colander._('"${val}" is not a datetime object',
                            mapping={'val':appstruct})
                          )
        return appstruct
Example #15
0
    def serialize(self, node, appstruct):
        if appstruct is null:
            return null

        try:
            return self.num(appstruct)
        except Exception:
            raise Invalid(
                node, _('"${val}" is not a number', mapping={'val':
                                                             appstruct}))
Example #16
0
    def deserialize(self, node, cstruct):
        if cstruct is colander.null:
            return colander.null

        if not colander.is_nonstr_iter(cstruct):
            raise colander.Invalid(
                node,
                colander._('${cstruct} is not iterable',
                           mapping={'cstruct': cstruct}))

        return ",".join(cstruct)
Example #17
0
    def deserialize(self, node, cstruct):
        if not cstruct:
            raise Invalid(node, _('Required'))

        try:
            r = urlparse.urlparse(cstruct)
            # require absolute urls
            if not r.scheme or not r.netloc or not r.hostname:
                raise Exception()
            # poke at stuff to make sure the parts are valid:
            r.port
            r.username
            r.password
            return r
        except Exception:
            e = sys.exc_info()[1]
            raise Invalid(node,
                          _('"${val}" is not a URL (${err})',
                            mapping={'val':cstruct, 'err': e})
                          )
Example #18
0
 def serialize(self, node, appstruct):
     if appstruct is null:
         return null
     
     try:
         return appstruct.geturl()
     except Exception:
         raise Invalid(node,
                       _('"${val}" is not a urlparse.ParseResult',
                         mapping={'val':appstruct}),
                       )
Example #19
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        try:
            if isinstance(cstruct, self.num):
                return self.num(cstruct)
        except Exception:
            pass

        raise Invalid(node, _('"${val}" is not a number', mapping={'val': cstruct}))
Example #20
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if not isinstance(cstruct, compat.string_types):
            raise Invalid(
                node,
                _("cstruct, currently type {}, must be a string".format(
                    type(cstruct))))

        return self.decoder(cstruct)  # noqa
Example #21
0
 def serialize(self, node, appstruct):
     if not appstruct:
         return colander.null
     if not ILocation.providedBy(appstruct):
         raise colander.Invalid(node, colander._('"${val}" object has not provide ILocation',
                                                 mapping={'val': appstruct}))
     bindings = node.bindings or {}
     request = bindings.get('request', None)
     if not request:
         raise RuntimeError('"request" has not found inside of schema node bindings')
     return request.resource_url(appstruct)
Example #22
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if cstruct == "any":
            return "0.0.0.0/0"

        try:
            return IPNetwork(cstruct, version=self._version)
        except:
            raise Invalid(node, _("must be a string representation of an IP address or CIDR"))
Example #23
0
    def serialize(self, node, appstruct):
        if appstruct is null:
            return null

        if not isinstance(appstruct, six.binary_type):
            raise Invalid(
                node,
                _("appstruct, currently type {}, must be a byte string ".
                  format(type(appstruct))))

        return self.encoder(appstruct)  # noqa
Example #24
0
 def __call__(self, node, value):
     try:
         phone = phonenumbers.parse(value)
     except phonenumbers.NumberParseException:
         raise Invalid(
             node,
             _(
                 u"Phone must be in format +XXXXXXXXXXX "
                 u"and contains country code",
                 mapping={'val': value}
             )
         )
     if not phonenumbers.is_valid_number(phone):
         raise Invalid(
             node,
             _(
                 u"Phone is not valid",
                 mapping={'val': value}
             )
         )
Example #25
0
    def serialize(self, node, appstruct):
        if appstruct is null:
            return null

        try:
            return appstruct.geturl()
        except Exception:
            raise Invalid(
                node,
                _('"${val}" is not a urlparse.ParseResult',
                  mapping={'val': appstruct}),
            )
Example #26
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        try:
            if isinstance(cstruct, self.num):
                return self.num(cstruct)
        except Exception:
            pass

        raise Invalid(node,
                      _('"${val}" is not a number', mapping={'val': cstruct}))
Example #27
0
    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        if not isinstance(appstruct, pytz.tzinfo.BaseTzInfo):
            raise colander.Invalid(
                node,
                colander._(
                    '"${val}" is not a known timezone',
                    mapping={"val": appstruct},
                ),
            )

        return appstruct.zone
Example #28
0
    def deserialize(self, node, cstruct):
        if not cstruct:
            raise Invalid(node, _('Required'))

        try:
            r = urlparse.urlparse(cstruct)
            # require absolute urls
            if not r.scheme or not r.netloc or not r.hostname:
                raise Exception()
            # poke at stuff to make sure the parts are valid:
            r.port
            r.username
            r.password
            return r
        except Exception:
            e = sys.exc_info()[1]
            raise Invalid(
                node,
                _('"${val}" is not a URL (${err})',
                  mapping={
                      'val': cstruct,
                      'err': e
                  }))
Example #29
0
    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

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

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

        return appstruct.strftime("%m/%d/%Y")
Example #30
0
 def deserialize(self, node, cstruct):
     if not cstruct:
         return null
     try:
         result = parse_date(cstruct, locale=get_locale_name())
     except:
         raise Invalid(
             node,
             _(
                 self.err_template,
                 mapping={'val': cstruct}
             )
         )
     return result
Example #31
0
    def deserialize(self, node, cstruct):
        if cstruct is colander.null:
            return colander.null

        try:
            return pytz.timezone(cstruct)
        except exceptions.UnknownTimeZoneError:
            raise colander.Invalid(
                node,
                colander._(
                    '"${val}" is an invalid timezone',
                    mapping={"val": cstruct},
                ),
            )
    def deserialize(self, node, cstruct):
        if cstruct is colander.null:
            return colander.null

        if not colander.is_nonstr_iter(cstruct):
            raise colander.Invalid(
                node,
                colander._(
                    '${cstruct} is not iterable',
                    mapping={'cstruct': cstruct}
                )
            )

        return ",".join(cstruct)
Example #33
0
    def deserialize(self, node, cstruct):
        if not cstruct:
            return colander.null

        # If time (presumably separated from date by a space) is present, discard it.
        if ' ' in cstruct:
            date, time = cstruct.split(' ', 1)
        else:
            date = cstruct

        try:
            month, day, year = map(int, date.split('/', 2))
            result = datetime.date(year, month, day)
        except Exception, e:
            raise colander.Invalid(node, colander._(self.err_template, mapping={'val':cstruct, 'err':e}))
Example #34
0
    def deserialize(self, node, cstruct):
        if not cstruct:
            return colander.null
        bindings = node.bindings or {}
        request = bindings.get('request', None)
        if not request:
            raise RuntimeError(
                '"request" has not found inside of schema node bindings')

        resource_path = urlsplit(cstruct).path
        try:
            resource = find_resource(request.root, resource_path)
        except KeyError:
            raise colander.Invalid(node, colander._('Resource has not found'))
        return resource
Example #35
0
    def deserialize(self, node, cstruct):
        if cstruct == '' and self.allow_empty:
            return {}

        if not cstruct:
            return colander.null

        if not cstruct.startswith('{'):
            raise colander.Invalid(
                node,
                colander._('${val} does not represent a JSON object',
                           mapping={'val': cstruct}))
        try:
            result = json.loads(cstruct)
        except json.JSONDecodeError as e:
            raise colander.Invalid(
                node,
                colander._('${val} is not a JSON object: ${err}',
                           mapping={
                               'val': cstruct,
                               'err': e
                           }))

        return result
Example #36
0
 def deserialize(self, node, cstruct):
     if not cstruct:
         return null
     try:
         # Now Babel does not understand time without seconds
         cstruct = "%s:00" % cstruct
         result = parse_time(cstruct, locale=get_locale_name())
     except:
         raise Invalid(
             node,
             _(
                 self.err_template,
                 mapping={'val': cstruct}
             )
         )
     return result
Example #37
0
    def serialize(self, node, appstruct):
        if appstruct is colander.null:
            return colander.null

        if type(appstruct) is datetime.date: # can't use isinstance; dt subs date
            appstruct = datetime.datetime.combine(appstruct, datetime.time())

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

        appstruct = convert_datetime(appstruct, pytz.utc, self.timezone)
        #return appstruct.strftime("%m/%d/%Y %I:%M %p")
        return appstruct.strftime("%m/%d/%Y %I:%M %p").lower()
Example #38
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if isinstance(cstruct, bool):
            return cstruct

        try:
            result = str(cstruct)
        except:
            raise Invalid(node, _('${val} is not a boolean', mapping={'val': cstruct}))
        result = result.lower()

        if result in ('false', '0'):
            return False

        return True
Example #39
0
    def deserialize(self, node, cstruct):
        if cstruct is null:
            return null

        if isinstance(cstruct, bool):
            return cstruct

        try:
            result = str(cstruct)
        except:
            raise Invalid(
                node, _('${val} is not a boolean', mapping={'val': cstruct}))
        result = result.lower()

        if result in ('false', '0'):
            return False

        return True
Example #40
0
    def __impl(self, node, value, callback, serializing, unknown):  # noqa
        error = None
        result = collections.OrderedDict()

        value = value.copy()
        for num, subnode in enumerate(node.children):
            name = subnode.name
            subval = value.pop(name, colander.null)

            # Skip the `drop` values early, as we are not allowed to pass them to
            # the schema node.
            if subval is colander.drop:
                continue
            if subval is colander.null:
                if serializing and subnode.default is colander.drop:
                    continue
                if not serializing and subnode.missing is colander.drop:
                    continue
            try:
                sub_result = callback(subnode, subval)
            except colander.Invalid as e:
                if error is None:
                    error = colander.Invalid(node)
                error.add(e, num)
            else:
                if sub_result is colander.drop:
                    continue
                result[name] = sub_result

        if unknown == "raise":
            if value:
                raise colander.UnsupportedFields(
                    node,
                    value,
                    msg=colander._('Unrecognized keys in mapping: "${val}"',
                                   mapping={'val': value}))

        elif unknown == "preserve":
            result.update(value)

        if error is not None:
            raise error  # pylint: disable=raising-bad-type

        return result
Example #41
0
    def deserialize(self, node, cstruct):
        if cstruct is colander.null:
            return colander.null

        try:
            result = cstruct
            if isinstance(result, (colander.text_type, bytes)):
                if self.encoding:
                    result = colander.text_(cstruct, self.encoding)
                else:
                    result = colander.text_type(cstruct)
            else:
                result = colander.text_type(cstruct)
        except Exception as e:
            raise colander.Invalid(node,
                                   colander._('${val} is not a string: ${err}',
                                              mapping={'val': cstruct, 'err': e}))

        return result
Example #42
0
 def translate_error(node, value):
     min_err = _(_('${val} is less than minimum value ${min}'), 
                 mapping={'val':'value', 'min':'min'})
     raise Invalid(node, min_err)
Example #43
0
import re

import colander

# Custom url validator that allow c2cgeoportal static urls.
URL_REGEX = r"(?:{}|^(:?static|config)://\S+$)".format(colander.URL_REGEX)
url = colander.Regex(URL_REGEX,
                     msg=colander._("Must be a URL"),
                     flags=re.IGNORECASE)
Example #44
0
 def __call__(self, node, value):
     if value in self.choices:
         err = colander._('"${val}" is not allowed value',
                          mapping={'val': value})
         raise colander.Invalid(node, err)
Example #45
0
 def excercise_translator(self, t):
     assert t.gettext('term') == 'term'
     assert t.ngettext('term', 'terms', 2) == 'terms'
     assert t.ngettext(_('term'), _('terms'), 1) == 'term'
     assert t.ngettext(_('term'), _('terms'), 2) == 'terms'
Example #46
0
 def excercise_translator(self, t):
     assert t.gettext('term') == 'term'
     assert t.ngettext('term', 'terms', 2) == 'terms'
     assert t.ngettext(_('term'), _('terms'), 1) == 'term'
     assert t.ngettext(_('term'), _('terms'), 2) == 'terms'      
Example #47
0
import colander
import re

# Custom url validator that allow c2cgeoportal static urls.
URL_REGEX = r'(?:{}|^(:?static|config)://\S+$)'.format(colander.URL_REGEX)
url = colander.Regex(URL_REGEX, msg=colander._('Must be a URL'), flags=re.IGNORECASE)