示例#1
0
 def _check_range(self, value):
     assert isinstance(value, (int, long))
     if self.min_value is not None and value < self.min_value:
         raise FieldValueError(public_message=(
             u'{} is lesser than {}'.format(value, self.min_value)))
     if self.max_value is not None and value > self.max_value:
         raise FieldValueError(public_message=(
             u'{} is greater than {}'.format(value, self.max_value)))
示例#2
0
文件: validators.py 项目: tensts/n6
def make_val_ldap_safe(val):
    val = val.strip()
    if val.startswith('#'):
        raise FieldValueError(
            public_message='Value: {value!r} cannot start with "#" symbol.'.format(value=val))
    illegal_char = _check_for_illegal_chars(illegal_characters_for_ldap, val)
    if illegal_char is not False:
        raise FieldValueError(
            public_message='Value: {value!r} contains illegal character: {char!r}.'.format(
                value=val, char=illegal_char))
    return val
示例#3
0
文件: validators.py 项目: tensts/n6
def to_stripped(val):
    if not isinstance(val, basestring):
        raise FieldValueError(public_message='Illegal type of value for a string-type field.')
    if isinstance(val, str):
        try:
            val = val.decode('utf-8', 'strict')
        except UnicodeDecodeError as exc:
            raise FieldValueError(
                public_message=invalid_field_template_msg.format(value=val, exc=exc))
    assert isinstance(val, unicode)
    return val.strip()
示例#4
0
 def _parse_datetime_string(value):
     try:
         return parse_iso_datetime_to_utc(value)
     except Exception:
         raise FieldValueError(public_message=(
             u'"{}" is not a valid date + '
             u'time specification'.format(ascii_str(value))))
示例#5
0
文件: validators.py 项目: tensts/n6
def ascii_only_to_unicode_stripped(val):
    if isinstance(val, unicode):
        try:
            val.encode('ascii', 'strict')  # just to check against encoding errors
        except UnicodeEncodeError as exc:
            raise FieldValueError(
                public_message=invalid_field_template_msg.format(value=val, exc=exc))
    else:
        assert isinstance(val, str)
        try:
            val = val.decode('ascii', 'strict')
        except UnicodeDecodeError as exc:
            raise FieldValueError(
                public_message=invalid_field_template_msg.format(value=val, exc=exc))
    assert isinstance(val, unicode)
    return val.strip()
示例#6
0
 def _validate_value(self, value):
     super(UnicodeEnumField, self)._validate_value(value)
     if value not in self.enum_values:
         raise FieldValueError(
             public_message=(u'"{}" is not one of: {}'.format(
                 ascii_str(value), u', '.join(u'"{}"'.format(v)
                                              for v in self.enum_values))))
示例#7
0
文件: validators.py 项目: tensts/n6
def validate_time_hour_minute_only(val):
    hour_minute_format = '%H:%M'
    try:
        datetime.datetime.strptime(val, hour_minute_format)
    except (TypeError, ValueError) as exc:
        raise FieldValueError(public_message=invalid_field_template_msg.format(value=val, exc=exc))
    return val
示例#8
0
 def _iter_clean_param_items(self, params, keys):
     error_info_seq = []
     for key in keys:
         assert key in self._all_param_fields
         assert key in params
         field = self._all_param_fields[key]
         param_values = params[key]
         assert param_values and type(param_values) is list
         assert hasattr(field, 'single_param')
         if field.single_param and len(param_values) > 1:
             error_info_seq.append(
                 (key, param_values,
                  FieldValueError(public_message=(
                      u'Multiple values for a single-value-only field.'))))
         else:
             cleaned_values = []
             for value in param_values:
                 try:
                     cleaned_val = field.clean_param_value(value)
                 except Exception as exc:
                     error_info_seq.append((key, value, exc))
                 else:
                     cleaned_values.append(cleaned_val)
             if cleaned_values:
                 yield key, cleaned_values
     if error_info_seq:
         raise ParamValueCleaningError(error_info_seq)
示例#9
0
    def clean_param_value(self, value):
        """
        The input `value` should be such a (:class:`str` or
        :class:`unicode`) string that ``value.lower()`` is equal to one
        of:

        * ``""`` or ``"yes"``, or ``"y"``, or ``"true"``, or ``"t"``, or
          ``"1"``, or ``"on"`` -- then the resultant cleaned value will
          be :obj:`True`;

        * ``"no"`` or ``"n"``, or ``"false"``, or ``"f"``, or ``"0"``,
          or ``"off"`` -- then the resultant cleaned value will be
          :obj:`False`;

        Note that when an empty string is given the resultant cleaned
        value will be :obj:`True` (!); thanks to this rule, a flag can
        be set by specifying the apropriate URL query parameter with no
        value (i.e., by using just its name).

        Returns: a :class:`bool` object (:obj:`True` or :obj:`False`).
        """
        value = super(FlagField, self).clean_param_value(value)
        if not value:
            return True
        value = value.lower()
        try:
            value = string_to_bool(value)
        except ValueError:
            raise FieldValueError(
                public_message=(string_to_bool.PUBLIC_MESSAGE_PATTERN.format(
                    ascii_str(value))))
        return value
示例#10
0
 def _fix_value(self, value):
     value = super(IPv6Field, self)._fix_value(value)
     try:
         ipv6_obj = ipaddr.IPv6Address(value)
     except Exception:
         raise FieldValueError(public_message=(
             self.error_msg_template.format(ascii_str(value))))
     return ipv6_obj
示例#11
0
 def _fix_value(self, value):
     value = super(DomainNameSubstringField, self)._fix_value(value)
     try:
         ascii_value = value.encode('idna')
     except ValueError:
         raise FieldValueError(
             public_message=(u'"{}" could not be encoded using the '
                             u'IDNA encoding'.format(ascii_str(value))))
     return unicode(ascii_value.lower())
示例#12
0
 def _fix_value(self, value):
     value = super(IPv6NetField, self)._fix_value(value)
     try:
         if '/' not in value:
             raise ValueError
         ipv6_network_obj = ipaddr.IPv6Network(value)
     except Exception:
         raise FieldValueError(public_message=(
             self.error_msg_template.format(ascii_str(value))))
     return ipv6_network_obj
示例#13
0
 def clean_result_value(self, value):
     if not isinstance(value, basestring):
         try:
             ip, net = value
             value = '{}/{}'.format(ip, net)
         except (ValueError, TypeError):
             raise FieldValueError(public_message=(
                 self.error_msg_template.format(ascii_str(value))))
     # returning a unicode string
     return super(IPv4NetField, self).clean_result_value(value)
示例#14
0
 def _validate_value(self, value):
     super(HexDigestField, self)._validate_value(value)
     try:
         value.decode('hex')
         if len(value) != self.num_of_characters:
             raise ValueError
     except (TypeError, ValueError):
         raise FieldValueError(
             public_message=(u'"{}" is not a valid {} hash'.format(
                 ascii_str(value), self.hash_algo_descr)))
示例#15
0
 def _clean_value(self, value):
     try:
         value = self._coerce_value(value)
         self._check_range(value)
     except FieldValueError:
         if self.error_msg_template is None:
             raise
         raise FieldValueError(public_message=(
             self.error_msg_template.format(ascii_str(value))))
     return value
示例#16
0
 def _fix_value(self, value):
     if isinstance(value, str):
         try:
             value = value.decode(self.encoding, self.decode_error_handling)
         except UnicodeError:
             raise FieldValueError(public_message=(
                 u'"{}" cannot be decoded with encoding "{}"'.format(
                     ascii_str(value), self.encoding)))
     assert isinstance(value, unicode)
     return value
示例#17
0
 def clean_result_value(self, value):
     str = unicode  #3--
     if not isinstance(value, (str, bytes, bytearray)):
         try:
             ip, net = value
             value = '{}/{}'.format(as_unicode(ip), as_unicode(net))
         except (ValueError, TypeError):
             raise FieldValueError(public_message=(
                 self.error_msg_template.format(ascii_str(value))))
     # returning a str
     return super(IPv4NetField, self).clean_result_value(value)
示例#18
0
 def _fix_value(self, value):
     if isinstance(value, (bytes, bytearray)):
         try:
             value = value.decode(self.encoding, self.decode_error_handling)
         except UnicodeError:
             raise FieldValueError(public_message=(
                 u'"{}" cannot be decoded with encoding "{}"'.format(
                     ascii_str(value), self.encoding)))
     assert isinstance(value, unicode)  #3: `unicode`->`str`
     if self.auto_strip:
         value = value.strip()
     return value
示例#19
0
 def _coerce_value(self, value):
     try:
         coerced_value = self._do_coerce(value)
         # e.g. float is OK *only* if it is an integer number (such as 42.0)
         if not isinstance(value, basestring) and coerced_value != value:
             raise ValueError
     except (TypeError, ValueError):
         raise FieldValueError(
             public_message=(u'"{}" cannot be interpreted as an '
                             u'integer number'.format(ascii_str(value))))
     assert isinstance(coerced_value, (int, long))  # long if > sys.maxint
     return coerced_value
示例#20
0
 def _fix_value(self, value):
     value = super(IPv6Field, self)._fix_value(value)
     try:
         _, _, last_segment = value.rpartition(':')
         if '.' in last_segment and not IPv4_STRICT_DECIMAL_REGEX.search(
                 last_segment):
             raise ValueError('{!r} is not a valid IPv4-like suffix'.format(
                 last_segment))
         ipv6_obj = ipaddress.IPv6Address(value)
     except Exception:
         raise FieldValueError(public_message=(
             self.error_msg_template.format(ascii_str(value))))
     return ipv6_obj
示例#21
0
 def _coerce_value(self, value):
     try:
         coerced_value = self._do_coerce(value)
         # e.g. float is OK *only* if it is an integer number (such as 42.0)
         str = unicode  #3--
         if not isinstance(
                 value, (str, bytes, bytearray)) and coerced_value != value:
             raise ValueError
     except (TypeError, ValueError):
         raise FieldValueError(
             public_message=(u'"{}" cannot be interpreted as an '
                             u'integer number'.format(ascii_str(value))))
     assert isinstance(coerced_value, (int, long))  #3: `long`--
     return coerced_value
示例#22
0
 def _validate_value(self, value):
     super(HexDigestField, self)._validate_value(value)
     try:
         if hasattr(bytes, 'fromhex'):  #3--
             bytes.fromhex(value)  #3: keep just `bytes.fromhex(value)`
         else:
             value.decode('hex')  #3--
         if len(value) != self.num_of_characters:
             raise ValueError('expected length: {!r} (got: {!r})'.format(
                 self.num_of_characters, len(value)))
     except (TypeError, ValueError):
         raise FieldValueError(
             public_message=(u'"{}" is not a valid {} hash'.format(
                 ascii_str(value), self.hash_algo_descr)))
示例#23
0
文件: fields.py 项目: CERT-Polska/n6
 def _urlsafe_b64decode(self, value):
     value = value.rstrip(
         '\r\n')  # some encoders like to append a newline...
     try:
         # `base64.urlsafe_b64decode()` just ignores illegal
         # characters *but* we want to be *more strict*
         if not self._URLSAFE_B64_VALID_CHARACTERS.issuperset(value):
             raise ValueError
         value = base64.urlsafe_b64decode(value)
     except ValueError:
         # (^ also `binascii.Error` may be raised but
         # it is a subclass of `ValueError` anyway)
         raise FieldValueError(public_message=(
             '"{}" is not a valid URL-safe-Base64-encoded string '
             '[see: RFC 4648, section 5]'.format(ascii_str(value))))
     return value
示例#24
0
文件: fields.py 项目: scottwedge/n6
 def _urlsafe_b64decode(self, value):
     value = value.rstrip('\r\n')  # some encoders like to append a newline...
     try:
         # `base64.urlsafe_b64decode()` just ignores illegal
         # characters *but* we want to be *more strict*
         if not self._URLSAFE_B64_VALID_CHARACTERS.issuperset(value):
             raise ValueError
         # `base64.urlsafe_b64decode()` (contrary to `base64.standard_b64decode()`)
         # does *not* accept unicode strings (even not pure-ASCII ones) :-/
         value = string_as_bytes(value)
         value = base64.urlsafe_b64decode(value)
     except (ValueError, TypeError):  # (TypeError is raised on incorrect Base64 padding)
         raise FieldValueError(public_message=(
             '"{}" is not a valid URL-safe-Base64-encoded string '
             '[see: RFC 4648, section 5]'.format(ascii_str(value))))
     return value
示例#25
0
 def clean_result_value(self, value):
     str = unicode  #3--
     if not isinstance(value, (str, bytes, bytearray)):
         try:
             ipv6_raw, prefixlen_raw = value
             value = '{}/{}'.format(as_unicode(ipv6_raw),
                                    as_unicode(prefixlen_raw))
         except (ValueError, TypeError):
             raise FieldValueError(public_message=(
                 self.error_msg_template.format(ascii_str(value))))
     ipv6_obj, prefixlen = super(IPv6NetField,
                                 self).clean_result_value(value)
     assert isinstance(ipv6_obj, ipaddress.IPv6Address)
     ipv6 = str(ipv6_obj.compressed)  #3: `str(`-- `)`--
     assert isinstance(ipv6, str)
     assert isinstance(prefixlen, int) and 0 <= prefixlen <= 128, prefixlen
     # returning a str
     return str('{}/{}'.format(ipv6, prefixlen))  #3: `str(`-- `)`--
示例#26
0
 def _iter_clean_param_items(self, params, keys):
     error_info_seq = []
     for key in keys:
         assert key in self._all_param_fields
         assert key in params
         field = self._all_param_fields[key]
         param_values = params[key]
         if not (isinstance(param_values, list) and all(
                 isinstance(val, (str,
                                  unicode))  #3: `unicode`--, just `str`
                 for val in param_values)):
             safe_repr_func = (
                 (lambda obj: ascii_str(object.__repr__(obj)))
                 if field.sensitive else repr)  #3: `repr`->`ascii`
             raise TypeError('{}={}, not being a list of str'.format(
                 key, safe_repr_func(param_values)))
         assert param_values
         assert hasattr(field, 'single_param')
         if field.single_param and len(param_values) > 1:
             safe_values = list(
                 self._get_value_or_safe_replacement(field, value)
                 for value in param_values)
             error_info_seq.append(
                 (key, safe_values,
                  FieldValueError(public_message=(
                      u'Multiple values for a single-value-only field.'))))
         else:
             cleaned_values = []
             for value in param_values:
                 try:
                     cleaned_val = field.clean_param_value(value)
                 except Exception as exc:
                     error_info_seq.append((
                         key,
                         self._get_value_or_safe_replacement(field, value),
                         self._get_safe_exc(field, exc),
                     ))
                 else:
                     cleaned_values.append(cleaned_val)
             if cleaned_values:
                 yield key, cleaned_values
     if error_info_seq:
         raise ParamValueCleaningError(error_info_seq)
示例#27
0
 def _fix_value(self, value):
     value = super(IPv6NetField, self)._fix_value(value)
     try:
         ipv6_str, prefixlen_str = value.split('/')
         _, _, last_segment = ipv6_str.rpartition(':')
         if '.' in last_segment and not IPv4_STRICT_DECIMAL_REGEX.search(
                 last_segment):
             raise ValueError('{!r} is not a valid IPv4-like suffix '
                              'of the address part'.format(last_segment))
         ipv6_obj = ipaddress.IPv6Address(ipv6_str)
         prefixlen = int(prefixlen_str)
         if str(prefixlen) != prefixlen_str:
             raise ValueError('{!r} != {!r}'.format(str(prefixlen),
                                                    prefixlen_str))
         if not 0 <= prefixlen <= 128:
             raise ValueError('{!r} not in range 0..128'.format(prefixlen))
     except Exception:
         raise FieldValueError(public_message=(
             self.error_msg_template.format(ascii_str(value))))
     return ipv6_obj, prefixlen
示例#28
0
 def _get_safe_exc(self, field, exc):
     if field.sensitive and not getattr(exc, 'safe_for_sensitive', False):
         return FieldValueError(
             public_message=field.default_error_msg_if_sensitive)
     return exc
示例#29
0
 def _validate_value(self, value):
     if self.disallow_empty and not value:
         raise FieldValueError(public_message=u'The value is empty')
示例#30
0
 def _validate_value(self, value):
     super(UnicodeRegexField, self)._validate_value(value)
     if self.regex.search(value) is None:
         raise FieldValueError(public_message=(
             self.error_msg_template.format(ascii_str(value))))