示例#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
示例#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)
示例#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
示例#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)
示例#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)
示例#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}))
示例#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"))
示例#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}))
示例#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}))
示例#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}))
示例#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)
示例#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}))
示例#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
示例#14
0
文件: base.py 项目: mrtopf/mongoquery
    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
示例#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}))
示例#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)
示例#17
0
文件: schemas.py 项目: B-Rich/wiseguy
    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})
                          )
示例#18
0
文件: schemas.py 项目: B-Rich/wiseguy
 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}),
                       )
示例#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}))
示例#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
示例#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)
示例#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"))
示例#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
示例#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}
             )
         )
示例#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}),
            )
示例#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}))
示例#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
示例#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
                  }))
示例#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")
示例#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
示例#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},
                ),
            )
示例#32
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)
示例#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}))
示例#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
示例#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
示例#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
示例#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()
示例#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
示例#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
示例#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
示例#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
示例#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)
示例#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)
示例#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)
示例#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'
示例#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'      
示例#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)