def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``True``, will check whether ``value`` can be coerced to a string if it is not already. Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum_length: If supplied, indicates the minimum number of characters needed to be valid. :type minimum_length: :class:`int <python:int>` :param maximum_length: If supplied, indicates the minimum number of characters needed to be valid. :type maximum_length: :class:`int <python:int>` :param whitespace_padding: If ``True`` and the value is below the ``minimum_length``, pad the value with spaces. Defaults to ``False``. :type whitespace_padding: :class:`bool <python:bool>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ if value is None: return False minimum_length = validators.integer(minimum_length, allow_empty = True, **kwargs) maximum_length = validators.integer(maximum_length, allow_empty = True, **kwargs) if isinstance(value, basestring) and not value: if minimum_length and minimum_length > 0 and not whitespace_padding: return False return True try: value = validators.string(value, coerce_value = coerce_value, minimum_length = minimum_length, maximum_length = maximum_length, whitespace_padding = whitespace_padding, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def max_retries(self): """The number of attempts to make on network connectivity-related API failures. :rtype: :class:`int <python:int>` """ if not self._max_retries: return validators.integer(os.getenv('BACKOFF_DEFAULT_TRIES', '3')) return self._max_retries
def video_capture_source(self, val: (str, int, None)): try: self._video_capture_source = validators.integer( val, coerce_value=True, allow_empty=True ) except TypeError: self._video_capture_source = validators.string( val, allow_empty=True )
def check_positive(value): """ Проверка, что введенное значение есть положительное целочисленное число :raises argparse.ArgumentTypeError: в случае невалидного значения """ try: return validators.integer(value, allow_empty=True, minimum=1) except errors.MinimumValueError: raise argparse.ArgumentTypeError(f'{value} should be positive number') except errors.NotAnIntegerError: raise argparse.ArgumentTypeError(f'{value} is not an integer')
def is_integer(value, coerce_value = False, minimum = None, maximum = None, base = 10, **kwargs): """Indicate whether ``value`` contains a whole number. :param value: The value to evaluate. :param coerce_value: If ``True``, will return ``True`` if ``value`` can be coerced to whole number. If ``False``, will only return ``True`` if ``value`` is already a whole number (regardless of type). Defaults to ``False``. :type coerce_value: :class:`bool <python:bool>` :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. :type minimum: numeric :param maximum: If supplied, will make sure that ``value`` is less than or equal to this value. :type maximum: numeric :param base: Indicates the base that is used to determine the integer value. The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to ``10``. :type base: :class:`int <python:int>` :returns: ``True`` if ``value`` is valid, ``False`` if it is not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ try: value = validators.integer(value, coerce_value = coerce_value, minimum = minimum, maximum = maximum, base = base, **kwargs) except SyntaxError as error: raise error except Exception: return False return True
def integer_validator(value, error_message='ingrese un número válido'): if value is None: return None if isinstance(value, bool): raise BadRequest(4010, error_message) try: data_valid = validators.integer(value, coerce_value=True, allow_empty=True) except Exception as e: raise BadRequest(4010, error_message) return data_valid
def check_for_errors(response, status_code, headers): """Check the HTTP Status Code and the response for errors and raise an appropriate exception. Otherwise return the result as-is. :param response: The content of the response. :type response: :class:`bytes <python:bytes>` :param status_code: The HTTP Status Code returned. :type status_code: :class:`int <python:int>` :param headers: The HTTP Headers returned. :type headers: :class:`dict <python:dict>` :returns: The content of the HTTP response, the status code of the HTTP response, and the headers of the HTTP response. :rtype: :class:`tuple <python:tuple>` of :class:`bytes <python:bytes>`, :class:`int <python:int>`, and :class:`dict <python:dict>` """ status_code = validators.integer(status_code, allow_empty=False) try: json_response = validators.json(response, allow_empty=True) except ValueError: if isinstance(response, bytes): response = response.decode('utf-8') json_response = validators.json(response, allow_empty=True) status_code, error_type, message = errors.parse_http_error( status_code, response) if not error_type: ws_status = json_response.get('status', None) error_value = errors.DEFAULT_ERROR_CODES.get(ws_status, None) if error_value: error_type = errors.ERROR_TYPES.get(error_value, None) if error_type: raise error_type(message) return response, status_code, headers
def max_retries(self, value): self._max_retries = validators.integer(value, allow_empty=True)
def rows(self, value): self._rows = validators.integer(value, allow_empty = False, coerce_value = False, minimum = 0)
def storage_width(self, value): self._storage_width = validators.integer(value, allow_empty = False, minimum = 0, coerce_value = True)
def from_integer(value): return validators.integer(value, allow_empty=True)
def from_timedelta(value): value = validators.integer(value, allow_empty=True) if value is None: return value return datetime.timedelta(seconds=value)
def backoff(to_execute, args = None, kwargs = None, strategy = None, retry_execute = None, retry_args = None, retry_kwargs = None, max_tries = None, max_delay = None, catch_exceptions = None, on_failure = None, on_success = None): """Retry a function call multiple times with a delay per the strategy given. :param to_execute: The function call that is to be attempted. :type to_execute: callable :param args: The positional arguments to pass to the function on the first attempt. If ``retry_args`` is :class:`None <python:None>`, will re-use these arguments on retry attempts as well. :type args: iterable / :class:`None <python:None>`. :param kwargs: The keyword arguments to pass to the function on the first attempt. If ``retry_kwargs`` is :class:`None <python:None>`, will re-use these keyword arguments on retry attempts as well. :type kwargs: :class:`dict <python:dict>` / :class:`None <python:None>` :param strategy: The :class:`BackoffStrategy` to use when determining the delay between retry attempts. If :class:`None <python:None>`, defaults to :class:`Exponential`. :type strategy: :class:`BackoffStrategy` :param retry_execute: The function to call on retry attempts. If :class:`None <python:None>`, will retry ``to_execute``. Defaults to :class:`None <python:None>`. :type retry_execute: callable / :class:`None <python:None>` :param retry_args: The positional arguments to pass to the function on retry attempts. If :class:`None <python:None>`, will re-use ``args``. Defaults to :class:`None <python:None>`. :type retry_args: iterable / :class:`None <python:None>` :param retry_kwargs: The keyword arguments to pass to the function on retry attempts. If :class:`None <python:None>`, will re-use ``kwargs``. Defaults to :class:`None <python:None>`. :type subsequent_kwargs: :class:`dict <python:dict>` / :class:`None <python:None>` :param max_tries: The maximum number of times to attempt the call. If :class:`None <python:None>`, will apply an environment variable ``BACKOFF_DEFAULT_TRIES``. If that environment variable is not set, will apply a default of ``3``. :type max_tries: int / :class:`None <python:None>` :param max_delay: The maximum number of seconds to wait befor giving up once and for all. If :class:`None <python:None>`, will apply an environment variable ``BACKOFF_DEFAULT_DELAY`` if that environment variable is set. If it is not set, will not apply a max delay at all. :type max_delay: :class:`None <python:None>` / int :param catch_exceptions: The ``type(exception)`` to catch and retry. If :class:`None <python:None>`, will catch all exceptions. Defaults to :class:`None <python:None>`. .. caution:: The iterable must contain one or more types of exception *instances*, and not class objects. For example: .. code-block:: python # GOOD: catch_exceptions = (type(ValueError()), type(TypeError())) # BAD: catch_exceptions = (type(ValueError), type(ValueError)) # BAD: catch_exceptions = (ValueError, TypeError) # BAD: catch_exceptions = (ValueError(), TypeError()) :type catch_exceptions: iterable of form ``[type(exception()), ...]`` :param on_failure: The :class:`exception <python:Exception>` or function to call when all retry attempts have failed. If :class:`None <python:None>`, will raise the last-caught :class:`exception <python:Exception>`. If an :class:`exception <python:Exception>`, will raise the exception with the same message as the last-caught exception. If a function, will call the function and pass the last-raised exception, its message, and stacktrace to the function. Defaults to :class:`None <python:None>`. :type on_failure: :class:`Exception <python:Exception>` / function / :class:`None <python:None>` :param on_success: The function to call when the operation was successful. The function receives the result of the ``to_execute`` or ``retry_execute`` function that was successful, and is called before that result is returned to whatever code called the backoff function. If :class:`None <python:None>`, will just return the result of ``to_execute`` or ``retry_execute`` without calling a handler. Defaults to :class:`None <python:None>`. :type on_success: callable / :class:`None <python:None>` :returns: The result of the attempted function. Example: .. code-block:: python from backoff_utils import backoff def some_function(arg1, arg2, kwarg1 = None): # Function does something pass result = backoff(some_function, args = ['value1', 'value2'], kwargs = { 'kwarg1': 'value3' }, max_tries = 3, max_delay = 30, strategy = strategies.Exponential) """ # pylint: disable=too-many-branches,too-many-statements if to_execute is None: raise ValueError('to_execute cannot be None') elif not checkers.is_callable(to_execute): raise TypeError('to_execute must be callable') if strategy is None: strategy = strategies.Exponential if not hasattr(strategy, 'IS_INSTANTIATED'): raise TypeError('strategy must be a BackoffStrategy or descendent') if not strategy.IS_INSTANTIATED: test_strategy = strategy(attempt = 0) else: test_strategy = strategy if not checkers.is_type(test_strategy, 'BackoffStrategy'): raise TypeError('strategy must be a BackoffStrategy or descendent') if args: args = validators.iterable(args) if kwargs: kwargs = validators.dict(kwargs) if retry_execute is None: retry_execute = to_execute elif not checkers.is_callable(retry_execute): raise TypeError('retry_execute must be None or a callable') if not retry_args: retry_args = args else: retry_args = validators.iterable(retry_args) if not retry_kwargs: retry_kwargs = kwargs else: retry_kwargs = validators.dict(retry_kwargs) if max_tries is None: max_tries = DEFAULT_MAX_TRIES max_tries = validators.integer(max_tries) if max_delay is None: max_delay = DEFAULT_MAX_DELAY if catch_exceptions is None: catch_exceptions = [type(Exception())] else: if not checkers.is_iterable(catch_exceptions): catch_exceptions = [catch_exceptions] catch_exceptions = validators.iterable(catch_exceptions) if on_failure is not None and not checkers.is_callable(on_failure): raise TypeError('on_failure must be None or a callable') if on_success is not None and not checkers.is_callable(on_success): raise TypeError('on_success must be None or a callable') cached_error = None return_value = None returned = False failover_counter = 0 start_time = datetime.utcnow() while failover_counter <= (max_tries): elapsed_time = (datetime.utcnow() - start_time).total_seconds() if max_delay is not None and elapsed_time >= max_delay: if cached_error is None: raise BackoffTimeoutError('backoff timed out after:' ' {}s'.format(elapsed_time)) else: _handle_failure(on_failure, cached_error) if failover_counter == 0: try: if args is not None and kwargs is not None: return_value = to_execute(*args, **kwargs) elif args is not None: return_value = to_execute(*args) elif kwargs is not None: return_value = to_execute(**kwargs) else: return_value = to_execute() returned = True break except Exception as error: # pylint: disable=broad-except if type(error) in catch_exceptions: cached_error = error strategy.delay(failover_counter) failover_counter += 1 continue else: _handle_failure(on_failure = on_failure, error = error) return else: try: if retry_args is not None and retry_kwargs is not None: return_value = retry_execute(*retry_args, **retry_kwargs) elif retry_args is not None: return_value = retry_execute(*retry_args) elif retry_kwargs is not None: return_value = retry_execute(**retry_kwargs) else: return_value = retry_execute() returned = True break except Exception as error: # pylint: disable=broad-except if type(error) in catch_exceptions: strategy.delay(failover_counter) cached_error = error failover_counter += 1 continue else: _handle_failure(on_failure = on_failure, error = error) return if not returned: _handle_failure(on_failure = on_failure, error = cached_error) return elif returned and on_success is not None: on_success(return_value) return return_value
def csv_sequence(self, value): if value is not None: value = validators.integer(value) self._csv_sequence = value
def bike_score(self, value): self._bike_score = validators.integer(value, allow_empty=True, minimum=0, maximum=100)
def status(self, value): self._status = validators.integer(value, allow_empty=True)
def _read_spss(data: Union[bytes, BytesIO, 'os.PathLike[Any]'], limit: Optional[int] = None, offset: int = 0, exclude_variables: Optional[List[str]] = None, include_variables: Optional[List[str]] = None, metadata_only: bool = False, apply_labels: bool = False, labels_as_categories: bool = True, missing_as_NaN: bool = False, convert_datetimes: bool = True, dates_as_datetime64: bool = False, **kwargs): """Internal function that reads an SPSS (.sav or .zsav) file and returns a :class:`tuple <python:tuple>` with a Pandas :class:`DataFrame <pandas:pandas.DataFrame>` object and a metadata :class:`dict <python:dict>`. :param data: The SPSS data to load. Accepts either a series of bytes or a filename. :type data: Path-like filename, :class:`bytes <python:bytes>` or :class:`BytesIO <python:io.bytesIO>` :param limit: The number of records to read from the data. If :obj:`None <python:None>` will return all records. Defaults to :obj:`None <python:None>`. :type limit: :class:`int <python:int>` or :obj:`None <python:None>` :param offset: The record at which to start reading the data. Defaults to 0 (first record). :type offset: :class:`int <python:int>` :param exclude_variables: A list of the variables that should be ignored when reading data. Defaults to :obj:`None <python:None>`. :type exclude_variables: iterable of :class:`str <python:str>` or :obj:`None <python:None>` :param include_variables: A list of the variables that should be explicitly included when reading data. Defaults to :obj:`None <python:None>`. :type include_variables: iterable of :class:`str <python:str>` or :obj:`None <python:None>` :param metadata_only: If ``True``, will return no data records in the resulting :class:`DataFrame <pandas:pandas.DataFrame>` but will return a complete metadata :class:`dict <python:dict>`. Defaults to ``False``. :type metadata_only: :class:`bool <python:bool>` :param apply_labels: If ``True``, converts the numerically-coded values in the raw data to their human-readable labels. Defaults to ``False``. :type apply_labels: :class:`bool <python:bool>` :param labels_as_categories: If ``True``, will convert labeled or formatted values to Pandas :term:`categories <pandas:category>`. Defaults to ``True``. .. caution:: This parameter will only have an effect if the ``apply_labels`` parameter is ``True``. :type labels_as_categories: :class:`bool <python:bool>` :param missing_as_NaN: If ``True``, will return any missing values as :class:`NaN <pandas:NaN>`. Otherwise will return missing values as per the configuration of missing value representation stored in the underlying SPSS data. Defaults to ``False``, which applies the missing value representation configured in the SPSS data itself. :type missing_as_NaN: :class:`bool <python:bool>` :param convert_datetimes: if ``True``, will convert the native integer representation of datetime values in the SPSS data to Pythonic :class:`datetime <python:datetime.datetime>`, or :class:`date <python:datetime.date>`, etc. representations (or Pandas :class:`datetime64 <pandas:datetime64>`, depending on the ``dates_as_datetime64`` parameter). If ``False``, will leave the original integer representation. Defaults to ``True``. :type convert_datetimes: :class:`bool <python:bool>` :param dates_as_datetime64: If ``True``, will return any date values as Pandas :class:`datetime64 <pandas.datetime64>` types. Defaults to ``False``. .. caution:: This parameter is only applied if ``convert_datetimes`` is set to ``True``. :type dates_as_datetime64: :class:`bool <python:bool>` :returns: A :class:`DataFrame <pandas:DataFrame>` representation of the SPSS data (or :obj:`None <python:None>`) and a :class:`Metadata` representation of the dataset's metadata / data map. :rtype: :class:`pandas.DataFrame <pandas:DataFrame>`/:obj:`None <python:None>` and :class:`Metadata` """ if not any([ checkers.is_file(data), checkers.is_bytesIO(data), checkers.is_type(data, bytes) ]): raise errors.InvalidDataFormatError( 'data must be a filename, BytesIO, or bytes ' f'object. Was: {data.__class__.__name__}') limit = validators.integer(limit, allow_empty=True, minimum=0) offset = validators.integer(offset, minimum=0) exclude_variables = validators.iterable(exclude_variables, allow_empty=True) if exclude_variables: exclude_variables = [validators.string(x) for x in exclude_variables] include_variables = validators.iterable(include_variables, allow_empty=True) if include_variables: include_variables = [validators.string(x) for x in include_variables] if not checkers.is_file(data): with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_file.write(data) temp_file_name = temp_file.name df, meta = pyreadstat.read_sav( temp_file_name, metadataonly=metadata_only, dates_as_pandas_datetime=dates_as_datetime64, apply_value_formats=apply_labels, formats_as_category=labels_as_categories, usecols=include_variables, user_missing=not missing_as_NaN, disable_datetime_conversion=not convert_datetimes, row_limit=limit or 0, row_offset=offset, **kwargs) os.remove(temp_file_name) else: df, meta = pyreadstat.read_sav( data, metadataonly=metadata_only, dates_as_pandas_datetime=dates_as_datetime64, apply_value_formats=apply_labels, formats_as_category=labels_as_categories, usecols=include_variables, user_missing=not missing_as_NaN, disable_datetime_conversion=not convert_datetimes, row_limit=limit or 0, row_offset=offset, **kwargs) metadata = Metadata.from_pyreadstat(meta) if exclude_variables: df = df.drop(exclude_variables, axis=1) if metadata.column_metadata: for variable in exclude_variables: metadata.column_metadata.pop(variable, None) return df, metadata