Example #1
0
    def time_period_str(self, value: str) -> timedelta:
        """Validate and transform time offset."""
        if isinstance(value, int):
            raise Invalid('Make sure you wrap time values in quotes')
        elif not isinstance(value, str):
            raise Invalid(TIME_PERIOD_ERROR.format(value))

        negative_offset = False
        if value.startswith('-'):
            negative_offset = True
            value = value[1:]
        elif value.startswith('+'):
            value = value[1:]

        try:
            parsed = [int(x) for x in value.split(':')]
        except ValueError:
            raise Invalid(TIME_PERIOD_ERROR.format(value))

        if len(parsed) == 2:
            hour, minute = parsed
            second = 0
        elif len(parsed) == 3:
            hour, minute, second = parsed
        else:
            raise Invalid(TIME_PERIOD_ERROR.format(value))

        offset = timedelta(hours=hour, minutes=minute, seconds=second)

        if negative_offset:
            offset *= -1

        return offset
Example #2
0
 def slugify(self, value):
     """Coerce a value to a slug."""
     if value is None:
         raise Invalid('Slug should not be None')
     slg = self._slugify(str(value))
     if slg:
         return slg
     raise Invalid('Unable to slugify {}'.format(value))
Example #3
0
        def validate(obj: Dict) -> Dict:
            """Test keys exist in dict."""
            if not isinstance(obj, dict):
                raise Invalid('expected dictionary')

            for k in obj.keys():
                if k in keys:
                    return obj
            raise Invalid('must contain one of {}.'.format(', '.join(keys)))
Example #4
0
        def validator(value):
            """Test dependencies."""
            if not isinstance(value, dict):
                raise Invalid('key dependencies require a dict')
            if key in value and dependency not in value:
                raise Invalid('dependency violation - key "{}" requires '
                                  'key "{}" to exist'.format(key, dependency))

            return value
Example #5
0
 def slug(self, value):
     """Validate value is a valid slug (aka: machine_label)"""
     if value is None:
         raise Invalid('Slug should not be None')
     value = str(value)
     slg = self._slugify(value)
     if value == slg:
         return value
     raise Invalid('invalid slug {} (try {})'.format(value, slg))
Example #6
0
 def slugify(self, value):
     """Coerce a value to a slug."""
     # print("going to try to slugify: %s" % value)
     if value is None:
         raise Invalid('Slug should not be None')
     slg = self._slugify(str(value))
     if slg:
         return slg
     # print("can't make slug: %s" % slg)
     raise Invalid('Unable to slugify {}'.format(value))
Example #7
0
    def is_file(self, value: Any) -> str:
        """Validate that the value is an existing file."""
        if value is None:
            raise Invalid('None is not file')
        file_in = os.path.expanduser(str(value))

        if not os.path.isfile(file_in):
            raise Invalid('not a file')
        if not os.access(file_in, os.R_OK):
            raise Invalid('file not readable')
        return file_in
Example #8
0
 def is_device(self, value):
     """Validate that value is a real device."""
     try:
         os.stat(value)
         return str(value)
     except OSError:
         raise Invalid('No device at {} found'.format(value))
Example #9
0
    def socket_timeout(value):
        """Validate timeout float > 0.0.

        None coerced to socket._GLOBAL_DEFAULT_TIMEOUT bare object.
        """
        if value is None:
            return _GLOBAL_DEFAULT_TIMEOUT
        else:
            try:
                float_value = float(value)
                if float_value > 0.0:
                    return float_value
                raise Invalid('Invalid socket timeout value.'
                                  ' float > 0.0 required.')
            except Exception as _:
                raise Invalid('Invalid socket timeout: {err}'.format(err=_))
Example #10
0
 def time_zone(self, value):
     """Validate timezone."""
     if self._Times.get_time_zone(value) is not None:
         return value
     raise Invalid(
         'Invalid time zone passed in. Valid options can be found here: '
         'http://en.wikipedia.org/wiki/List_of_tz_database_time_zones')
Example #11
0
 def temperature_unit(self, value) -> str:
     """Validate and transform temperature unit."""
     value = str(value).upper()
     if value == 'C':
         return TEMP_CELSIUS
     elif value == 'F':
         return TEMP_FAHRENHEIT
     raise Invalid('invalid temperature unit (expected C or F)')
Example #12
0
    def datetime(self, value):
        """Validate datetime."""
        if isinstance(value, datetime_sys):
            return value

        try:
            return self._Times.time_from_string(value)[0]
        except Exception:
            raise Invalid('Invalid datetime specified: {}'.format(value))
Example #13
0
 def x10_address(value):
     """Validate an x10 address."""
     regex = re.compile(r'([A-Pa-p]{1})(?:[2-9]|1[0-6]?)$')
     if not regex.match(value):
         raise Invalid('Invalid X10 Address')
     return str(value).lower()
Example #14
0
 def time(self, value):
     """Validate time."""
     try:
         return self._Times.time_from_string(value)[0]
     except Exception:
         raise Invalid('Invalid time specified: {}'.format(value))
Example #15
0
 def positive_timedelta(self, value: timedelta) -> timedelta:
     """Validate timedelta is positive."""
     if value < timedelta(0):
         raise Invalid('Time period should be positive')
     return value
Example #16
0
 def time_period_seconds(self, value: Union[int, str]) -> timedelta:
     """Validate and transform seconds to a time offset."""
     try:
         return timedelta(seconds=int(value))
     except (ValueError, TypeError):
         raise Invalid('Expected seconds, got {}'.format(value))