sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
|---|---|---|
def ensure_directory(directory):
"""
Create the directories along the provided directory path that do not exist.
"""
directory = os.path.expanduser(directory)
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise e
|
Create the directories along the provided directory path that do not exist.
|
entailment
|
def _process_validation_function_s(validation_func, # type: ValidationFuncs
auto_and_wrapper=True # type: bool
):
# type: (...) -> Union[Callable, List[Callable]]
"""
This function handles the various ways that users may enter 'validation functions', so as to output a single
callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead.
valid8 supports the following expressions for 'validation functions'
* <ValidationFunc>
* List[<ValidationFunc>(s)]. The list must not be empty.
<ValidationFunc> may either be
* a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically
'closed').
* a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of
valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type)
When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a
list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside
`or_` or `xor_`.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_`. Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all
functions. Otherwise a list is returned.
:return:
"""
# handle the case where validation_func is not yet a list or is empty or none
if validation_func is None:
raise ValueError('mandatory validation_func is None')
elif not isinstance(validation_func, list):
# so not use list() because we do not want to convert tuples here.
validation_func = [validation_func]
elif len(validation_func) == 0:
raise ValueError('provided validation_func list is empty')
# now validation_func is a non-empty list
final_list = []
for v in validation_func:
# special case of a LambdaExpression: automatically convert to a function
# note: we have to do it before anything else (such as .index) otherwise we may get failures
v = as_function(v)
if isinstance(v, tuple):
# convert all the tuples to failure raisers
if len(v) == 2:
if isinstance(v[1], str):
final_list.append(_failure_raiser(v[0], help_msg=v[1]))
elif isinstance(v[1], type) and issubclass(v[1], WrappingFailure):
final_list.append(_failure_raiser(v[0], failure_type=v[1]))
else:
raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation'
' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v)))
else:
raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation'
' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v)))
elif callable(v):
# use the validator directly
final_list.append(v)
elif isinstance(v, list):
# a list is an implicit and_, make it explicit
final_list.append(and_(*v))
else:
raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation'
' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v)))
# return what is required:
if auto_and_wrapper:
# a single callable doing the 'and'
return and_(*final_list)
else:
# or the list (typically for use inside or_(), xor_()...)
return final_list
|
This function handles the various ways that users may enter 'validation functions', so as to output a single
callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead.
valid8 supports the following expressions for 'validation functions'
* <ValidationFunc>
* List[<ValidationFunc>(s)]. The list must not be empty.
<ValidationFunc> may either be
* a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically
'closed').
* a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of
valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type)
When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a
list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside
`or_` or `xor_`.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_`. Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all
functions. Otherwise a list is returned.
:return:
|
entailment
|
def and_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a
`AtLeastOneFailed` failure on the first `False` received or `Exception` caught.
Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points
(`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...)
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
"""
validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False)
if len(validation_func) == 1:
return validation_func[0] # simplification for single validator case: no wrapper
else:
def and_v_(x):
for validator in validation_func:
try:
res = validator(x)
except Exception as e:
# one validator was unhappy > raise
raise AtLeastOneFailed(validation_func, x, cause=e)
if not result_is_success(res):
# one validator was unhappy > raise
raise AtLeastOneFailed(validation_func, x)
return True
and_v_.__name__ = 'and({})'.format(get_callable_names(validation_func))
return and_v_
|
An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a
`AtLeastOneFailed` failure on the first `False` received or `Exception` caught.
Note that an implicit `and_` is performed if you provide a list of validators to any of the entry points
(`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...)
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
|
entailment
|
def not_(validation_func, # type: ValidationFuncs
catch_all=False # type: bool
):
# type: (...) -> Callable
"""
Generates the inverse of the provided validation functions: when the validator returns `False` or raises a
`Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure.
By default, exceptions of types other than `Failure` are not caught and therefore fail the validation
(`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all
exceptions will be caught instead of just `Failure`s.
Note that you may use `not_all(<validation_functions_list>)` as a shortcut for
`not_(and_(<validation_functions_list>))`
:param validation_func: the base validation function. A callable, a tuple(callable, help_msg_str),
a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into
a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a
'ok' result
:return:
"""
def not_v_(x):
try:
res = validation_func(x)
if not result_is_success(res): # inverse the result
return True
except Failure:
return True # caught failure: always return True
except Exception as e:
if not catch_all:
raise e
else:
return True # caught exception in 'catch_all' mode: return True
# if we're here that's a failure
raise DidNotFail(wrapped_func=validation_func, wrong_value=x, validation_outcome=res)
not_v_.__name__ = 'not({})'.format(get_callable_name(validation_func))
return not_v_
|
Generates the inverse of the provided validation functions: when the validator returns `False` or raises a
`Failure`, this function returns `True`. Otherwise it raises a `DidNotFail` failure.
By default, exceptions of types other than `Failure` are not caught and therefore fail the validation
(`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all
exceptions will be caught instead of just `Failure`s.
Note that you may use `not_all(<validation_functions_list>)` as a shortcut for
`not_(and_(<validation_functions_list>))`
:param validation_func: the base validation function. A callable, a tuple(callable, help_msg_str),
a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into
a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a
'ok' result
:return:
|
entailment
|
def or_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be
silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details
about all validation results.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
"""
validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False)
if len(validation_func) == 1:
return validation_func[0] # simplification for single validator case
else:
def or_v_(x):
for validator in validation_func:
# noinspection PyBroadException
try:
res = validator(x)
if result_is_success(res):
# we can return : one validator was happy
return True
except Exception:
# catch all silently
pass
# no validator accepted: gather details and raise
raise AllValidatorsFailed(validation_func, x)
or_v_.__name__ = 'or({})'.format(get_callable_names(validation_func))
return or_v_
|
An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be
silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, together with details
about all validation results.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
|
entailment
|
def xor_(*validation_func # type: ValidationFuncs
):
# type: (...) -> Callable
"""
A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions
will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised,
together with details about the various validation results.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
"""
validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False)
if len(validation_func) == 1:
return validation_func[0] # simplification for single validation function case
else:
def xor_v_(x):
ok_validators = []
for val_func in validation_func:
# noinspection PyBroadException
try:
res = val_func(x)
if result_is_success(res):
ok_validators.append(val_func)
except Exception:
pass
# return if were happy or not
if len(ok_validators) == 1:
# one unique validation function happy: success
return True
elif len(ok_validators) > 1:
# several validation_func happy : fail
raise XorTooManySuccess(validation_func, x)
else:
# no validation function happy, fail
raise AllValidatorsFailed(validation_func, x)
xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func))
return xor_v_
|
A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions
will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFailed` will be raised,
together with details about the various validation results.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
|
entailment
|
def not_all(*validation_func, # type: ValidationFuncs
**kwargs
):
# type: (...) -> Callable
"""
An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into
a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a
'ok' result
:return:
"""
catch_all = pop_kwargs(kwargs, [('catch_all', False)])
# in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without
# wrapping it)
main_validator = and_(*validation_func)
return not_(main_validator, catch_all=catch_all)
|
An alias for not_(and_(validators)).
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into
a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a
'ok' result
:return:
|
entailment
|
def failure_raiser(*validation_func, # type: ValidationFuncs
**kwargs
):
# type: (...) -> Callable
"""
This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the
methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure
raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception)
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure
:param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with
no help message).
:param kw_context_args
:return:
"""
failure_type, help_msg = pop_kwargs(kwargs, [('failure_type', None), ('help_msg', None)], allow_others=True)
# the rest of keyword arguments is used as context.
kw_context_args = kwargs
main_func = _process_validation_function_s(list(validation_func))
return _failure_raiser(main_func, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
|
This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the
methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure
raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception)
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param failure_type: a subclass of `WrappingFailure` that should be raised in case of failure
:param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with
no help message).
:param kw_context_args
:return:
|
entailment
|
def pop_kwargs(kwargs,
names_with_defaults, # type: List[Tuple[str, Any]]
allow_others=False
):
"""
Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end.
:return:
"""
all_arguments = []
for name, default_ in names_with_defaults:
try:
val = kwargs.pop(name)
except KeyError:
val = default_
all_arguments.append(val)
if not allow_others and len(kwargs) > 0:
raise ValueError("Unsupported arguments: %s" % kwargs)
if len(names_with_defaults) == 1:
return all_arguments[0]
else:
return all_arguments
|
Internal utility method to extract optional arguments from kwargs.
:param kwargs:
:param names_with_defaults:
:param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end.
:return:
|
entailment
|
def get_details(self):
""" Overrides the base method in order to give details on the various successes and failures """
# transform the dictionary of failures into a printable form
need_to_print_value = True
failures_for_print = OrderedDict()
for validator, failure in self.failures.items():
name = get_callable_name(validator)
if isinstance(failure, Exception):
if isinstance(failure, WrappingFailure) or isinstance(failure, CompositionFailure):
need_to_print_value = False
failures_for_print[name] = '{exc_type}: {msg}'.format(exc_type=type(failure).__name__, msg=str(failure))
else:
failures_for_print[name] = str(failure)
if need_to_print_value:
value_str = ' for value [{val}]'.format(val=self.wrong_value)
else:
value_str = ''
# OrderedDict does not pretty print...
key_values_str = [repr(key) + ': ' + repr(val) for key, val in failures_for_print.items()]
failures_for_print_str = '{' + ', '.join(key_values_str) + '}'
# Note: we do note cite the value in the message since it is most probably available in inner messages [{val}]
msg = '{what}{possibly_value}. Successes: {success} / Failures: {fails}' \
''.format(what=self.get_what(), possibly_value=value_str,
success=self.successes, fails=failures_for_print_str)
return msg
|
Overrides the base method in order to give details on the various successes and failures
|
entailment
|
def play_all_validators(self, validators, value):
"""
Utility method to play all the provided validators on the provided value and output the
:param validators:
:param value:
:return:
"""
successes = list()
failures = OrderedDict()
for validator in validators:
name = get_callable_name(validator)
try:
res = validator(value)
if result_is_success(res):
successes.append(name)
else:
failures[validator] = res
except Exception as exc:
failures[validator] = exc
return successes, failures
|
Utility method to play all the provided validators on the provided value and output the
:param validators:
:param value:
:return:
|
entailment
|
def gen_secret(length=64):
""" Generates a secret of given length
"""
charset = string.ascii_letters + string.digits
return ''.join(random.SystemRandom().choice(charset)
for _ in range(length))
|
Generates a secret of given length
|
entailment
|
def encryptfile(filename, passphrase, algo='srp'):
"""
Encrypt a file and write it with .cryptoshop extension.
:param filename: a string with the path to the file to encrypt.
:param passphrase: a string with the user passphrase.
:param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp.
:return: a string with "successfully encrypted" or error.
"""
try:
if algo == "srp":
header = b"Cryptoshop srp " + b_version
crypto_algo = "Serpent/GCM"
if algo == "aes":
header = b"Cryptoshop aes " + b_version
crypto_algo = "AES-256/GCM"
if algo == "twf":
header = b"Cryptoshop twf " + b_version
crypto_algo = "Twofish/GCM"
if algo != "srp" and algo != "aes" and algo != "twf":
return "No valid algo. Use 'srp' 'aes' or 'twf'"
outname = filename + ".cryptoshop"
internal_key = botan.rng().get(internal_key_length)
# Passphrase derivation...
salt = botan.rng().get(__salt_size__)
masterkey = calc_derivation(passphrase=passphrase, salt=salt)
# Encrypt internal key...
encrypted_key = encry_decry_cascade(data=internal_key, masterkey=masterkey,
bool_encry=True,
assoc_data=header)
with open(filename, 'rb') as filestream:
file_size = os.stat(filename).st_size
if file_size == 0:
raise Exception("Error: You can't encrypt empty file.")
with open(str(outname), 'wb') as filestreamout:
filestreamout.write(header)
filestreamout.write(salt)
filestreamout.write(encrypted_key)
finished = False
# the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size
bar = tqdm(range(file_size // __chunk_size__))
while not finished:
chunk = filestream.read(__chunk_size__)
if len(chunk) == 0 or len(chunk) % __chunk_size__ != 0:
finished = True
# An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation.
encryptedchunk = encry_decry_chunk(chunk=chunk, key=internal_key, bool_encry=True,
algo=crypto_algo, assoc_data=header)
filestreamout.write(encryptedchunk)
bar.update(1)
return "successfully encrypted"
except IOError:
exit("Error: file \"" + filename + "\" was not found.")
|
Encrypt a file and write it with .cryptoshop extension.
:param filename: a string with the path to the file to encrypt.
:param passphrase: a string with the user passphrase.
:param algo: a string with the algorithm. Can be srp, aes, twf. Default is srp.
:return: a string with "successfully encrypted" or error.
|
entailment
|
def decryptfile(filename, passphrase):
"""
Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension.
:param filename: a string with the path to the file to decrypt.
:param passphrase: a string with the user passphrase.
:return: a string with "successfully decrypted" or error.
"""
try:
outname = os.path.splitext(filename)[0].split("_")[-1] # create a string file name without extension.
with open(filename, 'rb') as filestream:
file_size = os.stat(filename).st_size
if file_size == 0:
raise Exception("Error: You can't decrypt empty file.")
fileheader = filestream.read(header_length)
if fileheader == b"Cryptoshop srp " + b_version:
decrypt_algo = "Serpent/GCM"
if fileheader == b"Cryptoshop aes " + b_version:
decrypt_algo = "AES-256/GCM"
if fileheader == b"Cryptoshop twf " + b_version:
decrypt_algo = "Twofish/GCM"
if fileheader != b"Cryptoshop srp " + b_version and fileheader != b"Cryptoshop aes " + b_version and fileheader != b"Cryptoshop twf " + b_version:
raise Exception("Integrity failure: Bad header")
salt = filestream.read(__salt_size__)
encrypted_key = filestream.read(encrypted_key_length)
# Derive the passphrase...
masterkey = calc_derivation(passphrase=passphrase, salt=salt)
# Decrypt internal key...
try:
internal_key = encry_decry_cascade(data=encrypted_key, masterkey=masterkey,
bool_encry=False, assoc_data=fileheader)
except Exception as e:
return e
with open(str(outname), 'wb') as filestreamout:
files_size = os.stat(filename).st_size
# the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size
bar = tqdm(range(files_size // __chunk_size__))
while True:
# Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation.
encryptedchunk = filestream.read(__nonce_length__ + __gcmtag_length__ + __chunk_size__)
if len(encryptedchunk) == 0:
break
# Chunk decryption.
try:
original = encry_decry_chunk(chunk=encryptedchunk, key=internal_key, algo=decrypt_algo,
bool_encry=False, assoc_data=fileheader)
except Exception as e:
return e
else:
filestreamout.write(original)
bar.update(1)
return "successfully decrypted"
except IOError:
exit("Error: file \"" + filename + "\" was not found.")
|
Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension.
:param filename: a string with the path to the file to decrypt.
:param passphrase: a string with the user passphrase.
:return: a string with "successfully decrypted" or error.
|
entailment
|
def _tokenize(cls, sentence):
"""
Split a sentence while preserving tags.
"""
while True:
match = cls._regex_tag.search(sentence)
if not match:
yield from cls._split(sentence)
return
chunk = sentence[:match.start()]
yield from cls._split(chunk)
tag = match.group(0)
yield tag
sentence = sentence[(len(chunk) + len(tag)):]
|
Split a sentence while preserving tags.
|
entailment
|
def map(process, paths, threads=None):
"""
Implements a distributed stategy for processing XML files. This
function constructs a set of py:mod:`multiprocessing` threads (spread over
multiple cores) and uses an internal queue to aggregate outputs. To use
this function, implement a `process()` function that takes two arguments
-- a :class:`mwxml.Dump` and the path the dump was loaded
from. Anything that this function ``yield``s will be `yielded` in turn
from the :func:`mwxml.map` function.
:Parameters:
paths : `iterable` ( `str` | `file` )
a list of paths to dump files to process
process : `func`
A function that takes a :class:`~mwxml.iteration.dump.Dump` and the
path the dump was loaded from and yields
threads : int
the number of individual processing threads to spool up
:Example:
>>> import mwxml
>>> files = ["examples/dump.xml", "examples/dump2.xml"]
>>>
>>> def page_info(dump, path):
... for page in dump:
... yield page.id, page.namespace, page.title
...
>>> for id, namespace, title in mwxml.map(page_info, files):
... print(id, namespace, title)
...
"""
paths = [mwtypes.files.normalize_path(path) for path in paths]
def process_path(path):
dump = Dump.from_file(mwtypes.files.reader(path))
yield from process(dump, path)
yield from para.map(process_path, paths, mappers=threads)
|
Implements a distributed stategy for processing XML files. This
function constructs a set of py:mod:`multiprocessing` threads (spread over
multiple cores) and uses an internal queue to aggregate outputs. To use
this function, implement a `process()` function that takes two arguments
-- a :class:`mwxml.Dump` and the path the dump was loaded
from. Anything that this function ``yield``s will be `yielded` in turn
from the :func:`mwxml.map` function.
:Parameters:
paths : `iterable` ( `str` | `file` )
a list of paths to dump files to process
process : `func`
A function that takes a :class:`~mwxml.iteration.dump.Dump` and the
path the dump was loaded from and yields
threads : int
the number of individual processing threads to spool up
:Example:
>>> import mwxml
>>> files = ["examples/dump.xml", "examples/dump2.xml"]
>>>
>>> def page_info(dump, path):
... for page in dump:
... yield page.id, page.namespace, page.title
...
>>> for id, namespace, title in mwxml.map(page_info, files):
... print(id, namespace, title)
...
|
entailment
|
def dump(self):
"""Return the object itself."""
return {
'title': self.title,
'issue_id': self.issue_id,
'reporter': self.reporter,
'assignee': self.assignee,
'status': self.status,
'product': self.product,
'component': self.component,
'created_at': self.created_at,
'updated_at': self.updated_at,
'closed_at': self.closed_at,
'status_code': self.status_code
}
|
Return the object itself.
|
entailment
|
def apply_on_each_func_args_sig(func,
cur_args,
cur_kwargs,
sig, # type: Signature
func_to_apply,
func_to_apply_params_dict):
"""
Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs).
For each argument of func named 'att' in its signature, the following method is called:
`func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)`
:param func:
:param cur_args:
:param cur_kwargs:
:param sig:
:param func_to_apply:
:param func_to_apply_params_dict:
:return:
"""
# match the received arguments with the signature to know who is who
bound_values = sig.bind(*cur_args, **cur_kwargs)
# add the default values in here to get a full list
apply_defaults(bound_values)
for att_name, att_value in bound_values.arguments.items():
if att_name in func_to_apply_params_dict.keys():
# value = a normal value, or cur_kwargs as a whole
func_to_apply(att_value, func_to_apply_params_dict[att_name], func, att_name)
|
Applies func_to_apply on each argument of func according to what's received in current call (cur_args, cur_kwargs).
For each argument of func named 'att' in its signature, the following method is called:
`func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)`
:param func:
:param cur_args:
:param cur_kwargs:
:param sig:
:param func_to_apply:
:param func_to_apply_params_dict:
:return:
|
entailment
|
def is_product_owner(self, team_id):
"""Ensure the user is a PRODUCT_OWNER."""
if self.is_super_admin():
return True
team_id = uuid.UUID(str(team_id))
return team_id in self.child_teams_ids
|
Ensure the user is a PRODUCT_OWNER.
|
entailment
|
def is_in_team(self, team_id):
"""Test if user is in team"""
if self.is_super_admin():
return True
team_id = uuid.UUID(str(team_id))
return team_id in self.teams or team_id in self.child_teams_ids
|
Test if user is in team
|
entailment
|
def is_remoteci(self, team_id=None):
"""Ensure ther resource has the role REMOTECI."""
if team_id is None:
return self._is_remoteci
team_id = uuid.UUID(str(team_id))
if team_id not in self.teams_ids:
return False
return self.teams[team_id]['role'] == 'REMOTECI'
|
Ensure ther resource has the role REMOTECI.
|
entailment
|
def is_feeder(self, team_id=None):
"""Ensure ther resource has the role FEEDER."""
if team_id is None:
return self._is_feeder
team_id = uuid.UUID(str(team_id))
if team_id not in self.teams_ids:
return False
return self.teams[team_id]['role'] == 'FEEDER'
|
Ensure ther resource has the role FEEDER.
|
entailment
|
def document(self):
"""
:return: the :class:`Document` node that contains this node,
or ``self`` if this node is the document.
"""
if self.is_document:
return self
return self.adapter.wrap_document(self.adapter.impl_document)
|
:return: the :class:`Document` node that contains this node,
or ``self`` if this node is the document.
|
entailment
|
def root(self):
"""
:return: the root :class:`Element` node of the document that
contains this node, or ``self`` if this node is the root element.
"""
if self.is_root:
return self
return self.adapter.wrap_node(
self.adapter.impl_root_element, self.adapter.impl_document,
self.adapter)
|
:return: the root :class:`Element` node of the document that
contains this node, or ``self`` if this node is the root element.
|
entailment
|
def _convert_nodelist(self, impl_nodelist):
"""
Convert a list of underlying implementation nodes into a list of
*xml4h* wrapper nodes.
"""
nodelist = [
self.adapter.wrap_node(n, self.adapter.impl_document, self.adapter)
for n in impl_nodelist]
return NodeList(nodelist)
|
Convert a list of underlying implementation nodes into a list of
*xml4h* wrapper nodes.
|
entailment
|
def parent(self):
"""
:return: the parent of this node, or *None* of the node has no parent.
"""
parent_impl_node = self.adapter.get_node_parent(self.impl_node)
return self.adapter.wrap_node(
parent_impl_node, self.adapter.impl_document, self.adapter)
|
:return: the parent of this node, or *None* of the node has no parent.
|
entailment
|
def children(self):
"""
:return: a :class:`NodeList` of this node's child nodes.
"""
impl_nodelist = self.adapter.get_node_children(self.impl_node)
return self._convert_nodelist(impl_nodelist)
|
:return: a :class:`NodeList` of this node's child nodes.
|
entailment
|
def child(self, local_name=None, name=None, ns_uri=None, node_type=None,
filter_fn=None):
"""
:return: the first child node matching the given constraints, or \
*None* if there are no matching child nodes.
Delegates to :meth:`NodeList.filter`.
"""
return self.children(name=name, local_name=local_name, ns_uri=ns_uri,
node_type=node_type, filter_fn=filter_fn, first_only=True)
|
:return: the first child node matching the given constraints, or \
*None* if there are no matching child nodes.
Delegates to :meth:`NodeList.filter`.
|
entailment
|
def siblings(self):
"""
:return: a list of this node's sibling nodes.
:rtype: NodeList
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
return self._convert_nodelist(
[n for n in impl_nodelist if n != self.impl_node])
|
:return: a list of this node's sibling nodes.
:rtype: NodeList
|
entailment
|
def siblings_before(self):
"""
:return: a list of this node's siblings that occur *before* this
node in the DOM.
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
before_nodelist = []
for n in impl_nodelist:
if n == self.impl_node:
break
before_nodelist.append(n)
return self._convert_nodelist(before_nodelist)
|
:return: a list of this node's siblings that occur *before* this
node in the DOM.
|
entailment
|
def siblings_after(self):
"""
:return: a list of this node's siblings that occur *after* this
node in the DOM.
"""
impl_nodelist = self.adapter.get_node_children(self.parent.impl_node)
after_nodelist = []
is_after_myself = False
for n in impl_nodelist:
if is_after_myself:
after_nodelist.append(n)
elif n == self.impl_node:
is_after_myself = True
return self._convert_nodelist(after_nodelist)
|
:return: a list of this node's siblings that occur *after* this
node in the DOM.
|
entailment
|
def delete(self, destroy=True):
"""
Delete this node from the owning document.
:param bool destroy: if True the child node will be destroyed in
addition to being removed from the document.
:returns: the removed child node, or *None* if the child was destroyed.
"""
removed_child = self.adapter.remove_node_child(
self.adapter.get_node_parent(self.impl_node), self.impl_node,
destroy_node=destroy)
if removed_child is not None:
return self.adapter.wrap_node(removed_child, None, self.adapter)
else:
return None
|
Delete this node from the owning document.
:param bool destroy: if True the child node will be destroyed in
addition to being removed from the document.
:returns: the removed child node, or *None* if the child was destroyed.
|
entailment
|
def clone_node(self, node):
"""
Clone a node from another document to become a child of this node, by
copying the node's data into this document but leaving the node
untouched in the source document. The node to be cloned can be
a :class:`Node` based on the same underlying XML library implementation
and adapter, or a "raw" node from that implementation.
:param node: the node in another document to clone.
:type node: xml4h or implementation node
"""
if isinstance(node, xml4h.nodes.Node):
child_impl_node = node.impl_node
else:
child_impl_node = node # Assume it's a valid impl node
self.adapter.import_node(self.impl_node, child_impl_node, clone=True)
|
Clone a node from another document to become a child of this node, by
copying the node's data into this document but leaving the node
untouched in the source document. The node to be cloned can be
a :class:`Node` based on the same underlying XML library implementation
and adapter, or a "raw" node from that implementation.
:param node: the node in another document to clone.
:type node: xml4h or implementation node
|
entailment
|
def transplant_node(self, node):
"""
Transplant a node from another document to become a child of this node,
removing it from the source document. The node to be transplanted can
be a :class:`Node` based on the same underlying XML library
implementation and adapter, or a "raw" node from that implementation.
:param node: the node in another document to transplant.
:type node: xml4h or implementation node
"""
if isinstance(node, xml4h.nodes.Node):
child_impl_node = node.impl_node
original_parent_impl_node = node.parent.impl_node
else:
child_impl_node = node # Assume it's a valid impl node
original_parent_impl_node = self.adapter.get_node_parent(node)
self.adapter.import_node(self.impl_node, child_impl_node,
original_parent_impl_node, clone=False)
|
Transplant a node from another document to become a child of this node,
removing it from the source document. The node to be transplanted can
be a :class:`Node` based on the same underlying XML library
implementation and adapter, or a "raw" node from that implementation.
:param node: the node in another document to transplant.
:type node: xml4h or implementation node
|
entailment
|
def find(self, name=None, ns_uri=None, first_only=False):
"""
Find :class:`Element` node descendants of this node, with optional
constraints to limit the results.
:param name: limit results to elements with this name.
If *None* or ``'*'`` all element names are matched.
:type name: string or None
:param ns_uri: limit results to elements within this namespace URI.
If *None* all elements are matched, regardless of namespace.
:type ns_uri: string or None
:param bool first_only: if *True* only return the first result node
or *None* if there is no matching node.
:returns: a list of :class:`Element` nodes matching any given
constraints, or a single node if ``first_only=True``.
"""
if name is None:
name = '*' # Match all element names
if ns_uri is None:
ns_uri = '*' # Match all namespaces
impl_nodelist = self.adapter.find_node_elements(
self.impl_node, name=name, ns_uri=ns_uri)
if first_only:
if impl_nodelist:
return self.adapter.wrap_node(
impl_nodelist[0], self.adapter.impl_document, self.adapter)
else:
return None
return self._convert_nodelist(impl_nodelist)
|
Find :class:`Element` node descendants of this node, with optional
constraints to limit the results.
:param name: limit results to elements with this name.
If *None* or ``'*'`` all element names are matched.
:type name: string or None
:param ns_uri: limit results to elements within this namespace URI.
If *None* all elements are matched, regardless of namespace.
:type ns_uri: string or None
:param bool first_only: if *True* only return the first result node
or *None* if there is no matching node.
:returns: a list of :class:`Element` nodes matching any given
constraints, or a single node if ``first_only=True``.
|
entailment
|
def find_first(self, name=None, ns_uri=None):
"""
Find the first :class:`Element` node descendant of this node that
matches any optional constraints, or None if there are no matching
elements.
Delegates to :meth:`find` with ``first_only=True``.
"""
return self.find(name=name, ns_uri=ns_uri, first_only=True)
|
Find the first :class:`Element` node descendant of this node that
matches any optional constraints, or None if there are no matching
elements.
Delegates to :meth:`find` with ``first_only=True``.
|
entailment
|
def find_doc(self, name=None, ns_uri=None, first_only=False):
"""
Find :class:`Element` node descendants of the document containing
this node, with optional constraints to limit the results.
Delegates to :meth:`find` applied to this node's owning document.
"""
return self.document.find(name=name, ns_uri=ns_uri,
first_only=first_only)
|
Find :class:`Element` node descendants of the document containing
this node, with optional constraints to limit the results.
Delegates to :meth:`find` applied to this node's owning document.
|
entailment
|
def write(self, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize this node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param writer: an object such as a file or stream to which XML text
is sent. If *None* text is sent to :attr:`sys.stdout`.
:type writer: a file, stream, etc or None
:param string encoding: the character encoding for serialized text.
:param indent: indentation prefix to apply to descendent nodes for
pretty-printing. The value can take many forms:
- *int*: the number of spaces to indent. 0 means no indent.
- *string*: a literal prefix for indented nodes, such as ``\\t``.
- *bool*: no indent if *False*, four spaces indent if *True*.
- *None*: no indent
:type indent: string, int, bool, or None
:param newline: the string value used to separate lines of output.
The value can take a number of forms:
- *string*: the literal newline value, such as ``\\n`` or ``\\r``.
An empty string means no newline.
- *bool*: no newline if *False*, ``\\n`` newline if *True*.
- *None*: no newline.
:type newline: string, bool, or None
:param boolean omit_declaration: if *True* the XML declaration header
is omitted, otherwise it is included. Note that the declaration is
only output when serializing an :class:`xml4h.nodes.Document` node.
:param int node_depth: the indentation level to start at, such as 2 to
indent output as if the given *node* has two ancestors.
This parameter will only be useful if you need to output XML text
fragments that can be assembled into a document. This parameter
has no effect unless indentation is applied.
:param string quote_char: the character that delimits quoted content.
You should never need to mess with this.
Delegates to :func:`xml4h.writer.write_node` applied to this node.
"""
xml4h.write_node(self,
writer=writer, encoding=encoding, indent=indent,
newline=newline, omit_declaration=omit_declaration,
node_depth=node_depth, quote_char=quote_char)
|
Serialize this node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param writer: an object such as a file or stream to which XML text
is sent. If *None* text is sent to :attr:`sys.stdout`.
:type writer: a file, stream, etc or None
:param string encoding: the character encoding for serialized text.
:param indent: indentation prefix to apply to descendent nodes for
pretty-printing. The value can take many forms:
- *int*: the number of spaces to indent. 0 means no indent.
- *string*: a literal prefix for indented nodes, such as ``\\t``.
- *bool*: no indent if *False*, four spaces indent if *True*.
- *None*: no indent
:type indent: string, int, bool, or None
:param newline: the string value used to separate lines of output.
The value can take a number of forms:
- *string*: the literal newline value, such as ``\\n`` or ``\\r``.
An empty string means no newline.
- *bool*: no newline if *False*, ``\\n`` newline if *True*.
- *None*: no newline.
:type newline: string, bool, or None
:param boolean omit_declaration: if *True* the XML declaration header
is omitted, otherwise it is included. Note that the declaration is
only output when serializing an :class:`xml4h.nodes.Document` node.
:param int node_depth: the indentation level to start at, such as 2 to
indent output as if the given *node* has two ancestors.
This parameter will only be useful if you need to output XML text
fragments that can be assembled into a document. This parameter
has no effect unless indentation is applied.
:param string quote_char: the character that delimits quoted content.
You should never need to mess with this.
Delegates to :func:`xml4h.writer.write_node` applied to this node.
|
entailment
|
def xml(self, indent=4, **kwargs):
"""
:return: this node as XML text.
Delegates to :meth:`write`
"""
writer = StringIO()
self.write(writer, indent=indent, **kwargs)
return writer.getvalue()
|
:return: this node as XML text.
Delegates to :meth:`write`
|
entailment
|
def xpath(self, xpath, **kwargs):
"""
Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results of the query as a list of :class:`Node` objects, or
a list of base type objects if the XPath query does not reference
node objects.
"""
result = self.adapter.xpath_on_node(self.impl_node, xpath, **kwargs)
if isinstance(result, (list, tuple)):
return [self._maybe_wrap_node(r) for r in result]
else:
return self._maybe_wrap_node(result)
|
Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results of the query as a list of :class:`Node` objects, or
a list of base type objects if the XPath query does not reference
node objects.
|
entailment
|
def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict):
"""
Add or update this element's attributes, where attributes can be
specified in a number of ways.
:param attr_obj: a dictionary or list of attribute name/value pairs.
:type attr_obj: dict, list, tuple, or None
:param ns_uri: a URI defining a namespace for the new attributes.
:type ns_uri: string or None
:param dict attr_dict: attribute name and values specified as keyword
arguments.
"""
self._set_element_attributes(self.impl_node,
attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict)
|
Add or update this element's attributes, where attributes can be
specified in a number of ways.
:param attr_obj: a dictionary or list of attribute name/value pairs.
:type attr_obj: dict, list, tuple, or None
:param ns_uri: a URI defining a namespace for the new attributes.
:type ns_uri: string or None
:param dict attr_dict: attribute name and values specified as keyword
arguments.
|
entailment
|
def attributes(self):
"""
Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method which only updates and replaces them.
"""
attr_impl_nodes = self.adapter.get_node_attributes(self.impl_node)
return AttributeDict(attr_impl_nodes, self.impl_node, self.adapter)
|
Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method which only updates and replaces them.
|
entailment
|
def attribute_nodes(self):
"""
:return: a list of this element's attributes as
:class:`Attribute` nodes.
"""
impl_attr_nodes = self.adapter.get_node_attributes(self.impl_node)
wrapped_attr_nodes = [
self.adapter.wrap_node(a, self.adapter.impl_document, self.adapter)
for a in impl_attr_nodes]
return sorted(wrapped_attr_nodes, key=lambda x: x.name)
|
:return: a list of this element's attributes as
:class:`Attribute` nodes.
|
entailment
|
def attribute_node(self, name, ns_uri=None):
"""
:param string name: the name of the attribute to return.
:param ns_uri: a URI defining a namespace constraint on the attribute.
:type ns_uri: string or None
:return: this element's attributes that match ``ns_uri`` as
:class:`Attribute` nodes.
"""
attr_impl_node = self.adapter.get_node_attribute_node(
self.impl_node, name, ns_uri)
return self.adapter.wrap_node(
attr_impl_node, self.adapter.impl_document, self.adapter)
|
:param string name: the name of the attribute to return.
:param ns_uri: a URI defining a namespace constraint on the attribute.
:type ns_uri: string or None
:return: this element's attributes that match ``ns_uri`` as
:class:`Attribute` nodes.
|
entailment
|
def set_ns_prefix(self, prefix, ns_uri):
"""
Define a namespace prefix that will serve as shorthand for the given
namespace URI in element names.
:param string prefix: prefix that will serve as an alias for a
the namespace URI.
:param string ns_uri: namespace URI that will be denoted by the
prefix.
"""
self._add_ns_prefix_attr(self.impl_node, prefix, ns_uri)
|
Define a namespace prefix that will serve as shorthand for the given
namespace URI in element names.
:param string prefix: prefix that will serve as an alias for a
the namespace URI.
:param string ns_uri: namespace URI that will be denoted by the
prefix.
|
entailment
|
def add_element(self, name, ns_uri=None, attributes=None,
text=None, before_this_element=False):
"""
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:param string name: a name for the child node. The name may be used
to apply a namespace to the child by including:
- a prefix component in the name of the form
``ns_prefix:element_name``, where the prefix has already been
defined for a namespace URI (such as via :meth:`set_ns_prefix`).
- a literal namespace URI value delimited by curly braces, of
the form ``{ns_uri}element_name``.
:param ns_uri: a URI specifying the new element's namespace. If the
``name`` parameter specifies a namespace this parameter is ignored.
:type ns_uri: string or None
:param attributes: collection of attributes to assign to the new child.
:type attributes: dict, list, tuple, or None
:param text: text value to assign to the new child.
:type text: string or None
:param bool before_this_element: if *True* the new element is
added as a sibling preceding this element, instead of as a child.
In other words, the new element will be a child of this element's
parent node, and will immediately precent this element in the DOM.
:return: the new child as a an :class:`Element` node.
"""
# Determine local name, namespace and prefix info from tag name
prefix, local_name, node_ns_uri = \
self.adapter.get_ns_info_from_node_name(name, self.impl_node)
if prefix:
qname = u'%s:%s' % (prefix, local_name)
else:
qname = local_name
# If no name-derived namespace, apply an alternate namespace
if node_ns_uri is None:
if ns_uri is None:
# Default document namespace
node_ns_uri = self.adapter.get_ns_uri_for_prefix(
self.impl_node, None)
else:
# keyword-parameter namespace
node_ns_uri = ns_uri
# Create element
child_elem = self.adapter.new_impl_element(
qname, node_ns_uri, parent=self.impl_node)
# If element's default namespace was defined by literal uri prefix,
# create corresponding xmlns attribute for element...
if not prefix and '}' in name:
self._set_element_attributes(child_elem,
{'xmlns': node_ns_uri}, ns_uri=self.XMLNS_URI)
# ...otherwise define keyword-defined namespace as the default, if any
elif ns_uri is not None:
self._set_element_attributes(child_elem,
{'xmlns': ns_uri}, ns_uri=self.XMLNS_URI)
# Create subordinate nodes
if attributes is not None:
self._set_element_attributes(child_elem, attr_obj=attributes)
if text is not None:
self._add_text(child_elem, text)
# Add new element to its parent before a given node...
if before_this_element:
self.adapter.add_node_child(
self.adapter.get_node_parent(self.impl_node),
child_elem, before_sibling=self.impl_node)
# ...or in the default position, appended after existing nodes
else:
self.adapter.add_node_child(self.impl_node, child_elem)
return self.adapter.wrap_node(
child_elem, self.adapter.impl_document, self.adapter)
|
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:param string name: a name for the child node. The name may be used
to apply a namespace to the child by including:
- a prefix component in the name of the form
``ns_prefix:element_name``, where the prefix has already been
defined for a namespace URI (such as via :meth:`set_ns_prefix`).
- a literal namespace URI value delimited by curly braces, of
the form ``{ns_uri}element_name``.
:param ns_uri: a URI specifying the new element's namespace. If the
``name`` parameter specifies a namespace this parameter is ignored.
:type ns_uri: string or None
:param attributes: collection of attributes to assign to the new child.
:type attributes: dict, list, tuple, or None
:param text: text value to assign to the new child.
:type text: string or None
:param bool before_this_element: if *True* the new element is
added as a sibling preceding this element, instead of as a child.
In other words, the new element will be a child of this element's
parent node, and will immediately precent this element in the DOM.
:return: the new child as a an :class:`Element` node.
|
entailment
|
def add_text(self, text):
"""
Add a text node to this element.
Adding text with this method is subtly different from assigning a new
text value with :meth:`text` accessor, because it "appends" to rather
than replacing this element's set of text nodes.
:param text: text content to add to this element.
:param type: string or anything that can be coerced by :func:`unicode`.
"""
if not isinstance(text, basestring):
text = unicode(text)
self._add_text(self.impl_node, text)
|
Add a text node to this element.
Adding text with this method is subtly different from assigning a new
text value with :meth:`text` accessor, because it "appends" to rather
than replacing this element's set of text nodes.
:param text: text content to add to this element.
:param type: string or anything that can be coerced by :func:`unicode`.
|
entailment
|
def add_instruction(self, target, data):
"""
Add an instruction node to this element.
:param string text: text content to add as an instruction.
"""
self._add_instruction(self.impl_node, target, data)
|
Add an instruction node to this element.
:param string text: text content to add as an instruction.
|
entailment
|
def items(self):
"""
:return: a list of name/value attribute pairs sorted by attribute name.
"""
sorted_keys = sorted(self.keys())
return [(k, self[k]) for k in sorted_keys]
|
:return: a list of name/value attribute pairs sorted by attribute name.
|
entailment
|
def namespace_uri(self, name):
"""
:param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None.
"""
a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
if a_node is None:
return None
return self.adapter.get_node_namespace_uri(a_node)
|
:param string name: the name of an attribute to look up.
:return: the namespace URI associated with the named attribute,
or None.
|
entailment
|
def prefix(self, name):
"""
:param string name: the name of an attribute to look up.
:return: the prefix component of the named attribute's name,
or None.
"""
a_node = self.adapter.get_node_attribute_node(self.impl_element, name)
if a_node is None:
return None
return a_node.prefix
|
:param string name: the name of an attribute to look up.
:return: the prefix component of the named attribute's name,
or None.
|
entailment
|
def element(self):
"""
:return: the :class:`Element` that contains these attributes.
"""
return self.adapter.wrap_node(
self.impl_element, self.adapter.impl_document, self.adapter)
|
:return: the :class:`Element` that contains these attributes.
|
entailment
|
def filter(self, local_name=None, name=None, ns_uri=None, node_type=None,
filter_fn=None, first_only=False):
"""
Apply filters to the set of nodes in this list.
:param local_name: a local name used to filter the nodes.
:type local_name: string or None
:param name: a name used to filter the nodes.
:type name: string or None
:param ns_uri: a namespace URI used to filter the nodes.
If *None* all nodes are returned regardless of namespace.
:type ns_uri: string or None
:param node_type: a node type definition used to filter the nodes.
:type node_type: int node type constant, class, or None
:param filter_fn: an arbitrary function to filter nodes in this list.
This function must accept a single :class:`Node` argument and
return a bool indicating whether to include the node in the
filtered results.
.. note:: if ``filter_fn`` is provided all other filter arguments
are ignore.
:type filter_fn: function or None
:return: the type of the return value depends on the value of the
``first_only`` parameter and how many nodes match the filter:
- if ``first_only=False`` return a :class:`NodeList` of filtered
nodes, which will be empty if there are no matching nodes.
- if ``first_only=True`` and at least one node matches,
return the first matching :class:`Node`
- if ``first_only=True`` and there are no matching nodes,
return *None*
"""
# Build our own filter function unless a custom function is provided
if filter_fn is None:
def filter_fn(n):
# Test node type first in case other tests require this type
if node_type is not None:
# Node type can be specified as an integer constant (e.g.
# ELEMENT_NODE) or a class.
if isinstance(node_type, int):
if not n.is_type(node_type):
return False
elif n.__class__ != node_type:
return False
if name is not None and n.name != name:
return False
if local_name is not None and n.local_name != local_name:
return False
if ns_uri is not None and n.ns_uri != ns_uri:
return False
return True
# Filter nodes
nodelist = filter(filter_fn, self)
# If requested, return just the first node (or None if no nodes)
if first_only:
return nodelist[0] if nodelist else None
else:
return NodeList(nodelist)
|
Apply filters to the set of nodes in this list.
:param local_name: a local name used to filter the nodes.
:type local_name: string or None
:param name: a name used to filter the nodes.
:type name: string or None
:param ns_uri: a namespace URI used to filter the nodes.
If *None* all nodes are returned regardless of namespace.
:type ns_uri: string or None
:param node_type: a node type definition used to filter the nodes.
:type node_type: int node type constant, class, or None
:param filter_fn: an arbitrary function to filter nodes in this list.
This function must accept a single :class:`Node` argument and
return a bool indicating whether to include the node in the
filtered results.
.. note:: if ``filter_fn`` is provided all other filter arguments
are ignore.
:type filter_fn: function or None
:return: the type of the return value depends on the value of the
``first_only`` parameter and how many nodes match the filter:
- if ``first_only=False`` return a :class:`NodeList` of filtered
nodes, which will be empty if there are no matching nodes.
- if ``first_only=True`` and at least one node matches,
return the first matching :class:`Node`
- if ``first_only=True`` and there are no matching nodes,
return *None*
|
entailment
|
def get_all_analytics(user, job_id):
"""Get all analytics of a job."""
args = schemas.args(flask.request.args.to_dict())
v1_utils.verify_existence_and_get(job_id, models.JOBS)
query = v1_utils.QueryBuilder(_TABLE, args, _A_COLUMNS)
# If not admin nor rh employee then restrict the view to the team
if user.is_not_super_admin() and not user.is_read_only_user():
query.add_extra_condition(_TABLE.c.team_id.in_(user.teams_ids))
query.add_extra_condition(_TABLE.c.job_id == job_id)
nb_rows = query.get_number_of_rows()
rows = query.execute(fetchall=True)
rows = v1_utils.format_result(rows, _TABLE.name)
return flask.jsonify({'analytics': rows, '_meta': {'count': nb_rows}})
|
Get all analytics of a job.
|
entailment
|
def get_analytic(user, job_id, anc_id):
"""Get an analytic."""
v1_utils.verify_existence_and_get(job_id, models.JOBS)
analytic = v1_utils.verify_existence_and_get(anc_id, _TABLE)
analytic = dict(analytic)
if not user.is_in_team(analytic['team_id']):
raise dci_exc.Unauthorized()
return flask.jsonify({'analytic': analytic})
|
Get an analytic.
|
entailment
|
def write_node(node, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descendants will
be serialized.
:type node: an :class:`xml4h.nodes.Node` or subclass
:param writer: an object such as a file or stream to which XML text
is sent. If *None* text is sent to :attr:`sys.stdout`.
:type writer: a file, stream, etc or None
:param string encoding: the character encoding for serialized text.
:param indent: indentation prefix to apply to descendent nodes for
pretty-printing. The value can take many forms:
- *int*: the number of spaces to indent. 0 means no indent.
- *string*: a literal prefix for indented nodes, such as ``\\t``.
- *bool*: no indent if *False*, four spaces indent if *True*.
- *None*: no indent.
:type indent: string, int, bool, or None
:param newline: the string value used to separate lines of output.
The value can take a number of forms:
- *string*: the literal newline value, such as ``\\n`` or ``\\r``.
An empty string means no newline.
- *bool*: no newline if *False*, ``\\n`` newline if *True*.
- *None*: no newline.
:type newline: string, bool, or None
:param boolean omit_declaration: if *True* the XML declaration header
is omitted, otherwise it is included. Note that the declaration is
only output when serializing an :class:`xml4h.nodes.Document` node.
:param int node_depth: the indentation level to start at, such as 2 to
indent output as if the given *node* has two ancestors.
This parameter will only be useful if you need to output XML text
fragments that can be assembled into a document. This parameter
has no effect unless indentation is applied.
:param string quote_char: the character that delimits quoted content.
You should never need to mess with this.
"""
def _sanitize_write_value(value):
"""Return XML-encoded value."""
if not value:
return value
return (value
.replace("&", "&")
.replace("<", "<")
.replace("\"", """)
.replace(">", ">")
)
def _write_node_impl(node, node_depth):
"""
Internal write implementation that does the real work while keeping
track of node depth.
"""
# Output document declaration if we're outputting the whole doc
if node.is_document:
if not omit_declaration:
writer.write(
'<?xml version=%s1.0%s' % (quote_char, quote_char))
if encoding:
writer.write(' encoding=%s%s%s'
% (quote_char, encoding, quote_char))
writer.write('?>%s' % newline)
for child in node.children:
_write_node_impl(child,
node_depth) # node_depth not incremented
writer.write(newline)
elif node.is_document_type:
writer.write("<!DOCTYPE %s SYSTEM %s%s%s"
% (node.name, quote_char, node.public_id))
if node.system_id is not None:
writer.write(
" %s%s%s" % (quote_char, node.system_id, quote_char))
if node.children:
writer.write("[")
for child in node.children:
_write_node_impl(child, node_depth + 1)
writer.write("]")
writer.write(">")
elif node.is_text:
writer.write(_sanitize_write_value(node.value))
elif node.is_cdata:
if ']]>' in node.value:
raise ValueError("']]>' is not allowed in CDATA node value")
writer.write("<![CDATA[%s]]>" % node.value)
#elif node.is_entity_reference: # TODO
elif node.is_entity:
writer.write(newline + indent * node_depth)
writer.write("<!ENTITY ")
if node.is_paremeter_entity:
writer.write('%% ')
writer.write("%s %s%s%s>"
% (node.name, quote_char, node.value, quote_char))
elif node.is_processing_instruction:
writer.write(newline + indent * node_depth)
writer.write("<?%s %s?>" % (node.target, node.data))
elif node.is_comment:
if '--' in node.value:
raise ValueError("'--' is not allowed in COMMENT node value")
writer.write("<!--%s-->" % node.value)
elif node.is_notation:
writer.write(newline + indent * node_depth)
writer.write("<!NOTATION %s" % node.name)
if node.is_system_identifier:
writer.write(" system %s%s%s>"
% (quote_char, node.external_id, quote_char))
elif node.is_system_identifier:
writer.write(" system %s%s%s %s%s%s>"
% (quote_char, node.external_id, quote_char,
quote_char, node.uri, quote_char))
elif node.is_attribute:
writer.write(" %s=%s" % (node.name, quote_char))
writer.write(_sanitize_write_value(node.value))
writer.write(quote_char)
elif node.is_element:
# Only need a preceding newline if we're in a sub-element
if node_depth > 0:
writer.write(newline)
writer.write(indent * node_depth)
writer.write("<" + node.name)
for attr in node.attribute_nodes:
_write_node_impl(attr, node_depth)
if node.children:
found_indented_child = False
writer.write(">")
for child in node.children:
_write_node_impl(child, node_depth + 1)
if not (child.is_text
or child.is_comment
or child.is_cdata):
found_indented_child = True
if found_indented_child:
writer.write(newline + indent * node_depth)
writer.write('</%s>' % node.name)
else:
writer.write('/>')
else:
raise exceptions.Xml4hImplementationBug(
'Cannot write node with class: %s' % node.__class__)
# Sanitize whitespace parameters
if indent is True:
indent = ' ' * 4
elif indent is False:
indent = ''
elif isinstance(indent, int):
indent = ' ' * indent
# If indent but no newline set, always apply a newline (it makes sense)
if indent and not newline:
newline = True
if newline is None or newline is False:
newline = ''
elif newline is True:
newline = '\n'
# We always need a writer, use stdout by default
if writer is None:
writer = sys.stdout
# Apply a text encoding if we have one
if encoding is None:
writer = writer
else:
writer = codecs.getwriter(encoding)(writer)
# Do the business...
_write_node_impl(node, node_depth)
|
Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descendants will
be serialized.
:type node: an :class:`xml4h.nodes.Node` or subclass
:param writer: an object such as a file or stream to which XML text
is sent. If *None* text is sent to :attr:`sys.stdout`.
:type writer: a file, stream, etc or None
:param string encoding: the character encoding for serialized text.
:param indent: indentation prefix to apply to descendent nodes for
pretty-printing. The value can take many forms:
- *int*: the number of spaces to indent. 0 means no indent.
- *string*: a literal prefix for indented nodes, such as ``\\t``.
- *bool*: no indent if *False*, four spaces indent if *True*.
- *None*: no indent.
:type indent: string, int, bool, or None
:param newline: the string value used to separate lines of output.
The value can take a number of forms:
- *string*: the literal newline value, such as ``\\n`` or ``\\r``.
An empty string means no newline.
- *bool*: no newline if *False*, ``\\n`` newline if *True*.
- *None*: no newline.
:type newline: string, bool, or None
:param boolean omit_declaration: if *True* the XML declaration header
is omitted, otherwise it is included. Note that the declaration is
only output when serializing an :class:`xml4h.nodes.Document` node.
:param int node_depth: the indentation level to start at, such as 2 to
indent output as if the given *node* has two ancestors.
This parameter will only be useful if you need to output XML text
fragments that can be assembled into a document. This parameter
has no effect unless indentation is applied.
:param string quote_char: the character that delimits quoted content.
You should never need to mess with this.
|
entailment
|
def encry_decry_chunk(chunk, key, algo, bool_encry, assoc_data):
"""
When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False,
the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk.
:param chunk: a chunk in bytes to encrypt or decrypt.
:param key: a 32 bytes key in bytes.
:param algo: a string of algorithm. Can be "srp" , "AES" or "twf"
:param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted.
:param assoc_data: bytes string of additional data for GCM Authentication.
:return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk.
"""
engine = botan.cipher(algo=algo, encrypt=bool_encry)
engine.set_key(key=key)
engine.set_assoc_data(assoc_data)
if bool_encry is True:
nonce = generate_nonce_timestamp()
engine.start(nonce=nonce)
return nonce + engine.finish(chunk)
else:
nonce = chunk[:__nonce_length__]
encryptedchunk = chunk[__nonce_length__:__nonce_length__ + __gcmtag_length__ + __chunk_size__]
engine.start(nonce=nonce)
decryptedchunk = engine.finish(encryptedchunk)
if decryptedchunk == b"":
raise Exception("Integrity failure: Invalid passphrase or corrupted data")
return decryptedchunk
|
When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False,
the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk.
:param chunk: a chunk in bytes to encrypt or decrypt.
:param key: a 32 bytes key in bytes.
:param algo: a string of algorithm. Can be "srp" , "AES" or "twf"
:param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted.
:param assoc_data: bytes string of additional data for GCM Authentication.
:return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk.
|
entailment
|
def retrieve_info(self):
"""Query Bugzilla API to retrieve the needed infos."""
scheme = urlparse(self.url).scheme
netloc = urlparse(self.url).netloc
query = urlparse(self.url).query
if scheme not in ('http', 'https'):
return
for item in query.split('&'):
if 'id=' in item:
ticket_id = item.split('=')[1]
break
else:
return
bugzilla_url = '%s://%s/%s%s' % (scheme, netloc, _URI_BASE, ticket_id)
result = requests.get(bugzilla_url)
self.status_code = result.status_code
if result.status_code == 200:
tree = ElementTree.fromstring(result.content)
self.title = tree.findall("./bug/short_desc").pop().text
self.issue_id = tree.findall("./bug/bug_id").pop().text
self.reporter = tree.findall("./bug/reporter").pop().text
self.assignee = tree.findall("./bug/assigned_to").pop().text
self.status = tree.findall("./bug/bug_status").pop().text
self.product = tree.findall("./bug/product").pop().text
self.component = tree.findall("./bug/component").pop().text
self.created_at = tree.findall("./bug/creation_ts").pop().text
self.updated_at = tree.findall("./bug/delta_ts").pop().text
try:
self.closed_at = (
tree.findall("./bug/cf_last_closed").pop().text
)
except IndexError:
# cf_last_closed is present only if the issue has been closed
# if not present it raises an IndexError, meaning the issue
# isn't closed yet, which is a valid use case.
pass
|
Query Bugzilla API to retrieve the needed infos.
|
entailment
|
def minlen(min_length,
strict=False # type: bool
):
"""
'Minimum length' validation_function generator.
Returns a validation_function to check that len(x) >= min_length (strict=False, default)
or len(x) > min_length (strict=True)
:param min_length: minimum length for x
:param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len(x) > min_length
(strict=True)
:return:
"""
if strict:
def minlen_(x):
if len(x) > min_length:
return True
else:
# raise Failure('minlen: len(x) > ' + str(min_length) + ' does not hold for x=' + str(x))
raise TooShort(wrong_value=x, min_length=min_length, strict=True)
else:
def minlen_(x):
if len(x) >= min_length:
return True
else:
# raise Failure('minlen: len(x) >= ' + str(min_length) + ' does not hold for x=' + str(x))
raise TooShort(wrong_value=x, min_length=min_length, strict=False)
minlen_.__name__ = 'length_{}greater_than_{}'.format('strictly_' if strict else '', min_length)
return minlen_
|
'Minimum length' validation_function generator.
Returns a validation_function to check that len(x) >= min_length (strict=False, default)
or len(x) > min_length (strict=True)
:param min_length: minimum length for x
:param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len(x) > min_length
(strict=True)
:return:
|
entailment
|
def maxlen(max_length,
strict=False # type: bool
):
"""
'Maximum length' validation_function generator.
Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True)
:param max_length: maximum length for x
:param strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length
(strict=True)
:return:
"""
if strict:
def maxlen_(x):
if len(x) < max_length:
return True
else:
# raise Failure('maxlen: len(x) < ' + str(max_length) + ' does not hold for x=' + str(x))
raise TooLong(wrong_value=x, max_length=max_length, strict=True)
else:
def maxlen_(x):
if len(x) <= max_length:
return True
else:
# raise Failure('maxlen: len(x) <= ' + str(max_length) + ' does not hold for x=' + str(x))
raise TooLong(wrong_value=x, max_length=max_length, strict=False)
maxlen_.__name__ = 'length_{}lesser_than_{}'.format('strictly_' if strict else '', max_length)
return maxlen_
|
'Maximum length' validation_function generator.
Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True)
:param max_length: maximum length for x
:param strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length
(strict=True)
:return:
|
entailment
|
def has_length(ref_length):
"""
'length equals' validation function generator.
Returns a validation_function to check that `len(x) == ref_length`
:param ref_length:
:return:
"""
def has_length_(x):
if len(x) == ref_length:
return True
else:
raise WrongLength(wrong_value=x, ref_length=ref_length)
has_length_.__name__ = 'length_equals_{}'.format(ref_length)
return has_length_
|
'length equals' validation function generator.
Returns a validation_function to check that `len(x) == ref_length`
:param ref_length:
:return:
|
entailment
|
def length_between(min_len,
max_len,
open_left=False, # type: bool
open_right=False # type: bool
):
"""
'Is length between' validation_function generator.
Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left`
flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce
`min_len < len(x) <= max_len`.
:param min_len: minimum length for x
:param max_len: maximum length for x
:param open_left: Boolean flag to turn the left inequality to strict mode
:param open_right: Boolean flag to turn the right inequality to strict mode
:return:
"""
if open_left and open_right:
def length_between_(x):
if (min_len < len(x)) and (len(x) < max_len):
return True
else:
# raise Failure('length between: {} < len(x) < {} does not hold for x={}'.format(min_len, max_len,
# x))
raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len,
right_strict=True)
elif open_left:
def length_between_(x):
if (min_len < len(x)) and (len(x) <= max_len):
return True
else:
# raise Failure('length between: {} < len(x) <= {} does not hold for x={}'.format(min_len, max_len,
# x))
raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len,
right_strict=False)
elif open_right:
def length_between_(x):
if (min_len <= len(x)) and (len(x) < max_len):
return True
else:
# raise Failure('length between: {} <= len(x) < {} does not hold for x={}'.format(min_len, max_len,
# x))
raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len,
right_strict=True)
else:
def length_between_(x):
if (min_len <= len(x)) and (len(x) <= max_len):
return True
else:
# raise Failure('length between: {} <= len(x) <= {} does not hold for x={}'.format(min_len,
# max_len, x))
raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len,
right_strict=False)
length_between_.__name__ = 'length_between_{}_and_{}'.format(min_len, max_len)
return length_between_
|
'Is length between' validation_function generator.
Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left`
flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce
`min_len < len(x) <= max_len`.
:param min_len: minimum length for x
:param max_len: maximum length for x
:param open_left: Boolean flag to turn the left inequality to strict mode
:param open_right: Boolean flag to turn the right inequality to strict mode
:return:
|
entailment
|
def is_in(allowed_values # type: Set
):
"""
'Values in' validation_function generator.
Returns a validation_function to check that x is in the provided set of allowed values
:param allowed_values: a set of allowed values
:return:
"""
def is_in_allowed_values(x):
if x in allowed_values:
return True
else:
# raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(x))
raise NotInAllowedValues(wrong_value=x, allowed_values=allowed_values)
is_in_allowed_values.__name__ = 'is_in_{}'.format(allowed_values)
return is_in_allowed_values
|
'Values in' validation_function generator.
Returns a validation_function to check that x is in the provided set of allowed values
:param allowed_values: a set of allowed values
:return:
|
entailment
|
def is_subset(reference_set # type: Set
):
"""
'Is subset' validation_function generator.
Returns a validation_function to check that x is a subset of reference_set
:param reference_set: the reference set
:return:
"""
def is_subset_of(x):
missing = x - reference_set
if len(missing) == 0:
return True
else:
# raise Failure('is_subset: len(x - reference_set) == 0 does not hold for x=' + str(x)
# + ' and reference_set=' + str(reference_set) + '. x contains unsupported '
# 'elements ' + str(missing))
raise NotSubset(wrong_value=x, reference_set=reference_set, unsupported=missing)
is_subset_of.__name__ = 'is_subset_of_{}'.format(reference_set)
return is_subset_of
|
'Is subset' validation_function generator.
Returns a validation_function to check that x is a subset of reference_set
:param reference_set: the reference set
:return:
|
entailment
|
def contains(ref_value):
"""
'Contains' validation_function generator.
Returns a validation_function to check that `ref_value in x`
:param ref_value: a value that must be present in x
:return:
"""
def contains_ref_value(x):
if ref_value in x:
return True
else:
raise DoesNotContainValue(wrong_value=x, ref_value=ref_value)
contains_ref_value.__name__ = 'contains_{}'.format(ref_value)
return contains_ref_value
|
'Contains' validation_function generator.
Returns a validation_function to check that `ref_value in x`
:param ref_value: a value that must be present in x
:return:
|
entailment
|
def is_superset(reference_set # type: Set
):
"""
'Is superset' validation_function generator.
Returns a validation_function to check that x is a superset of reference_set
:param reference_set: the reference set
:return:
"""
def is_superset_of(x):
missing = reference_set - x
if len(missing) == 0:
return True
else:
# raise Failure('is_superset: len(reference_set - x) == 0 does not hold for x=' + str(x)
# + ' and reference_set=' + str(reference_set) + '. x does not contain required '
# 'elements ' + str(missing))
raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing)
is_superset_of.__name__ = 'is_superset_of_{}'.format(reference_set)
return is_superset_of
|
'Is superset' validation_function generator.
Returns a validation_function to check that x is a superset of reference_set
:param reference_set: the reference set
:return:
|
entailment
|
def on_all_(*validation_func):
"""
Generates a validation_function for collection inputs where each element of the input will be validated against the
validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced
with an 'and_'.
Note that if you want to apply DIFFERENT validation_functions for each element in the input, you should rather use
on_each_.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
"""
# create the validation functions
validation_function_func = _process_validation_function_s(list(validation_func))
def on_all_val(x):
# validate all elements in x in turn
for idx, x_elt in enumerate(x):
try:
res = validation_function_func(x_elt)
except Exception as e:
raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=e)
if not result_is_success(res):
# one element of x was not valid > raise
# raise Failure('on_all_(' + str(validation_func) + '): failed validation for input '
# 'element [' + str(idx) + ']: ' + str(x_elt))
raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=res)
return True
on_all_val.__name__ = 'apply_<{}>_on_all_elts'.format(get_callable_name(validation_function_func))
return on_all_val
|
Generates a validation_function for collection inputs where each element of the input will be validated against the
validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced
with an 'and_'.
Note that if you want to apply DIFFERENT validation_functions for each element in the input, you should rather use
on_each_.
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:return:
|
entailment
|
def on_each_(*validation_functions_collection):
"""
Generates a validation_function for collection inputs where each element of the input will be validated against the
corresponding validation_function(s) in the validation_functions_collection. Validators inside the tuple can be
provided as a list for convenience, this will be replaced with an 'and_' operator if the list has more than one
element.
Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use
on_all_.
:param validation_functions_collection: a sequence of (base validation function or list of base validation functions
to use).
A base validation function may be a callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or
a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list).
Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/)
expressions can be used instead of callables, they will be transformed to functions automatically.
:return:
"""
# create a tuple of validation functions.
validation_function_funcs = tuple(_process_validation_function_s(validation_func)
for validation_func in validation_functions_collection)
# generate a validation function based on the tuple of validation_functions lists
def on_each_val(x # type: Tuple
):
if len(validation_function_funcs) != len(x):
raise Failure('on_each_: x does not have the same number of elements than validation_functions_collection.')
else:
# apply each validation_function on the input with the same position in the collection
idx = -1
for elt, validation_function_func in zip(x, validation_function_funcs):
idx += 1
try:
res = validation_function_func(elt)
except Exception as e:
raise InvalidItemInSequence(wrong_value=elt,
wrapped_func=validation_function_func,
validation_outcome=e)
if not result_is_success(res):
# one validation_function was unhappy > raise
# raise Failure('on_each_(' + str(validation_functions_collection) + '): _validation_function [' + str(idx)
# + '] (' + str(validation_functions_collection[idx]) + ') failed validation for '
# 'input ' + str(x[idx]))
raise InvalidItemInSequence(wrong_value=elt,
wrapped_func=validation_function_func,
validation_outcome=res)
return True
on_each_val.__name__ = 'map_<{}>_on_elts' \
''.format('(' + ', '.join([get_callable_name(f) for f in validation_function_funcs]) + ')')
return on_each_val
|
Generates a validation_function for collection inputs where each element of the input will be validated against the
corresponding validation_function(s) in the validation_functions_collection. Validators inside the tuple can be
provided as a list for convenience, this will be replaced with an 'and_' operator if the list has more than one
element.
Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use
on_all_.
:param validation_functions_collection: a sequence of (base validation function or list of base validation functions
to use).
A base validation function may be a callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or
a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list).
Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/)
expressions can be used instead of callables, they will be transformed to functions automatically.
:return:
|
entailment
|
def get_jobs_events_from_sequence(user, sequence):
"""Get all the jobs events from a given sequence number."""
args = schemas.args(flask.request.args.to_dict())
if user.is_not_super_admin():
raise dci_exc.Unauthorized()
query = sql.select([models.JOBS_EVENTS]). \
select_from(models.JOBS_EVENTS.join(models.JOBS,
models.JOBS.c.id == models.JOBS_EVENTS.c.job_id)). \
where(_TABLE.c.id >= sequence)
sort_list = v1_utils.sort_query(args['sort'], _JOBS_EVENTS_COLUMNS,
default='created_at')
query = v1_utils.add_sort_to_query(query, sort_list)
if args.get('limit', None):
query = query.limit(args.get('limit'))
if args.get('offset', None):
query = query.offset(args.get('offset'))
rows = flask.g.db_conn.execute(query).fetchall()
query_nb_rows = sql.select([func.count(models.JOBS_EVENTS.c.id)])
nb_rows = flask.g.db_conn.execute(query_nb_rows).scalar()
return json.jsonify({'jobs_events': rows, '_meta': {'count': nb_rows}})
|
Get all the jobs events from a given sequence number.
|
entailment
|
def from_file(cls, f):
"""
Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer.
:Parameters:
f : `file`
A plain text file pointer containing XML to process
"""
element = ElementIterator.from_file(f)
assert element.tag == "mediawiki"
return cls.from_element(element)
|
Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer.
:Parameters:
f : `file`
A plain text file pointer containing XML to process
|
entailment
|
def from_page_xml(cls, page_xml):
"""
Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block.
:Parameters:
page_xml : `str` | `file`
Either a plain string or a file containing <page> block XML to
process
"""
header = """
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.5/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.5/
http://www.mediawiki.org/xml/export-0.5.xsd" version="0.5"
xml:lang="en">
<siteinfo>
</siteinfo>
"""
footer = "</mediawiki>"
return cls.from_file(mwtypes.files.concat(header, page_xml, footer))
|
Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block.
:Parameters:
page_xml : `str` | `file`
Either a plain string or a file containing <page> block XML to
process
|
entailment
|
def calc_derivation(passphrase, salt):
"""
Calculate a 32 bytes key derivation with Argon2.
:param passphrase: A string of any length specified by user.
:param salt: 512 bits generated by Botan Random Number Generator.
:return: a 32 bytes keys.
"""
argonhash = argon2.low_level.hash_secret_raw((str.encode(passphrase)), salt=salt, hash_len=32,
time_cost=__argon2_timing_cost__, memory_cost=__argon2_memory_cost__,
parallelism=__argon2_parallelism__, type=argon2.low_level.Type.I)
return argonhash
|
Calculate a 32 bytes key derivation with Argon2.
:param passphrase: A string of any length specified by user.
:param salt: 512 bits generated by Botan Random Number Generator.
:return: a 32 bytes keys.
|
entailment
|
def get_node_text(self, node):
"""
Return contatenated value of all text node children of this element
"""
text_children = [n.nodeValue for n in self.get_node_children(node)
if n.nodeType == xml.dom.Node.TEXT_NODE]
if text_children:
return u''.join(text_children)
else:
return None
|
Return contatenated value of all text node children of this element
|
entailment
|
def set_node_text(self, node, text):
"""
Set text value as sole Text child node of element; any existing
Text nodes are removed
"""
# Remove any existing Text node children
for child in self.get_node_children(node):
if child.nodeType == xml.dom.Node.TEXT_NODE:
self.remove_node_child(node, child, True)
if text is not None:
text_node = self.new_impl_text(text)
self.add_node_child(node, text_node)
|
Set text value as sole Text child node of element; any existing
Text nodes are removed
|
entailment
|
def _get_contents(self):
"""Create strings from glob strings."""
def files():
for value in super(GlobBundle, self)._get_contents():
for path in glob.glob(value):
yield path
return list(files())
|
Create strings from glob strings.
|
entailment
|
def is_generic_type(tp):
"""Test if the given type is a generic type. This includes Generic itself, but
excludes special typing constructs such as Union, Tuple, Callable, ClassVar.
Examples::
is_generic_type(int) == False
is_generic_type(Union[int, str]) == False
is_generic_type(Union[int, T]) == False
is_generic_type(ClassVar[List[int]]) == False
is_generic_type(Callable[..., T]) == False
is_generic_type(Generic) == True
is_generic_type(Generic[T]) == True
is_generic_type(Iterable[int]) == True
is_generic_type(Mapping) == True
is_generic_type(MutableMapping[T, List[int]]) == True
is_generic_type(Sequence[Union[str, bytes]]) == True
"""
if NEW_TYPING:
return (isinstance(tp, type) and issubclass(tp, Generic) or
isinstance(tp, _GenericAlias) and
tp.__origin__ not in (Union, tuple, ClassVar, collections.abc.Callable))
# SMA: refering to is_callable_type and is_tuple_type to avoid duplicate code
return isinstance(tp, GenericMeta) and not is_callable_type(tp) and not is_tuple_type(tp)
|
Test if the given type is a generic type. This includes Generic itself, but
excludes special typing constructs such as Union, Tuple, Callable, ClassVar.
Examples::
is_generic_type(int) == False
is_generic_type(Union[int, str]) == False
is_generic_type(Union[int, T]) == False
is_generic_type(ClassVar[List[int]]) == False
is_generic_type(Callable[..., T]) == False
is_generic_type(Generic) == True
is_generic_type(Generic[T]) == True
is_generic_type(Iterable[int]) == True
is_generic_type(Mapping) == True
is_generic_type(MutableMapping[T, List[int]]) == True
is_generic_type(Sequence[Union[str, bytes]]) == True
|
entailment
|
def is_union_type(tp):
"""Test if the type is a union type. Examples::
is_union_type(int) == False
is_union_type(Union) == True
is_union_type(Union[int, int]) == False
is_union_type(Union[T, int]) == True
"""
if NEW_TYPING:
return (tp is Union or
isinstance(tp, _GenericAlias) and tp.__origin__ is Union)
try:
from typing import _Union
return type(tp) is _Union
except ImportError:
# SMA: support for very old typing module <=3.5.3
return type(tp) is Union or type(tp) is type(Union)
|
Test if the type is a union type. Examples::
is_union_type(int) == False
is_union_type(Union) == True
is_union_type(Union[int, int]) == False
is_union_type(Union[T, int]) == True
|
entailment
|
def is_classvar(tp):
"""Test if the type represents a class variable. Examples::
is_classvar(int) == False
is_classvar(ClassVar) == True
is_classvar(ClassVar[int]) == True
is_classvar(ClassVar[List[T]]) == True
"""
if NEW_TYPING:
return (tp is ClassVar or
isinstance(tp, _GenericAlias) and tp.__origin__ is ClassVar)
try:
from typing import _ClassVar
return type(tp) is _ClassVar
except:
# SMA: support for very old typing module <=3.5.3
return False
|
Test if the type represents a class variable. Examples::
is_classvar(int) == False
is_classvar(ClassVar) == True
is_classvar(ClassVar[int]) == True
is_classvar(ClassVar[List[T]]) == True
|
entailment
|
def parse(to_parse, ignore_whitespace_text_nodes=True, adapter=None):
"""
Parse an XML document into an *xml4h*-wrapped DOM representation
using an underlying XML library implementation.
:param to_parse: an XML document file, document string, or the
path to an XML file. If a string value is given that contains
a ``<`` character it is treated as literal XML data, otherwise
a string value is treated as a file path.
:type to_parse: a file-like object or string
:param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace
nodes are stripped from the parsed document, since these are
usually noise introduced by XML docs serialized to be human-friendly.
:param adapter: the *xml4h* implementation adapter class used to parse
the document and to interact with the resulting nodes.
If None, :attr:`best_adapter` will be used.
:type adapter: adapter class or None
:return: an :class:`xml4h.nodes.Document` node representing the
parsed document.
Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or
:meth:`~xml4h.impls.interface.parse_file` implementation.
"""
if adapter is None:
adapter = best_adapter
if isinstance(to_parse, basestring) and '<' in to_parse:
return adapter.parse_string(to_parse, ignore_whitespace_text_nodes)
else:
return adapter.parse_file(to_parse, ignore_whitespace_text_nodes)
|
Parse an XML document into an *xml4h*-wrapped DOM representation
using an underlying XML library implementation.
:param to_parse: an XML document file, document string, or the
path to an XML file. If a string value is given that contains
a ``<`` character it is treated as literal XML data, otherwise
a string value is treated as a file path.
:type to_parse: a file-like object or string
:param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace
nodes are stripped from the parsed document, since these are
usually noise introduced by XML docs serialized to be human-friendly.
:param adapter: the *xml4h* implementation adapter class used to parse
the document and to interact with the resulting nodes.
If None, :attr:`best_adapter` will be used.
:type adapter: adapter class or None
:return: an :class:`xml4h.nodes.Document` node representing the
parsed document.
Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or
:meth:`~xml4h.impls.interface.parse_file` implementation.
|
entailment
|
def build(tagname_or_element, ns_uri=None, adapter=None):
"""
Return a :class:`~xml4h.builder.Builder` that represents an element in
a new or existing XML DOM and provides "chainable" methods focussed
specifically on adding XML content.
:param tagname_or_element: a string name for the root node of a
new XML document, or an :class:`~xml4h.nodes.Element` node in an
existing document.
:type tagname_or_element: string or :class:`~xml4h.nodes.Element` node
:param ns_uri: a namespace URI to apply to the new root node. This
argument has no effect this method is acting on an element.
:type ns_uri: string or None
:param adapter: the *xml4h* implementation adapter class used to
interact with the document DOM nodes.
If None, :attr:`best_adapter` will be used.
:type adapter: adapter class or None
:return: a :class:`~xml4h.builder.Builder` instance that represents an
:class:`~xml4h.nodes.Element` node in an XML DOM.
"""
if adapter is None:
adapter = best_adapter
if isinstance(tagname_or_element, basestring):
doc = adapter.create_document(
tagname_or_element, ns_uri=ns_uri)
element = doc.root
elif isinstance(tagname_or_element, xml4h.nodes.Element):
element = tagname_or_element
else:
raise xml4h.exceptions.IncorrectArgumentTypeException(
tagname_or_element, [basestring, xml4h.nodes.Element])
return Builder(element)
|
Return a :class:`~xml4h.builder.Builder` that represents an element in
a new or existing XML DOM and provides "chainable" methods focussed
specifically on adding XML content.
:param tagname_or_element: a string name for the root node of a
new XML document, or an :class:`~xml4h.nodes.Element` node in an
existing document.
:type tagname_or_element: string or :class:`~xml4h.nodes.Element` node
:param ns_uri: a namespace URI to apply to the new root node. This
argument has no effect this method is acting on an element.
:type ns_uri: string or None
:param adapter: the *xml4h* implementation adapter class used to
interact with the document DOM nodes.
If None, :attr:`best_adapter` will be used.
:type adapter: adapter class or None
:return: a :class:`~xml4h.builder.Builder` instance that represents an
:class:`~xml4h.nodes.Element` node in an XML DOM.
|
entailment
|
def get_none_policy_text(none_policy, # type: int
verbose=False # type: bool
):
"""
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy
:param none_policy:
:param verbose:
:return:
"""
if none_policy is NonePolicy.SKIP:
return "accept None without performing validation" if verbose else 'SKIP'
elif none_policy is NonePolicy.FAIL:
return "fail on None without performing validation" if verbose else 'FAIL'
elif none_policy is NonePolicy.VALIDATE:
return "validate None as any other values" if verbose else 'VALIDATE'
elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_FAIL:
return "accept None without validation if the argument is optional, otherwise fail on None" if verbose \
else 'SKIP_IF_NONABLE_ELSE_FAIL'
elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE:
return "accept None without validation if the argument is optional, otherwise validate None as any other " \
"values" if verbose else 'SKIP_IF_NONABLE_ELSE_VALIDATE'
else:
raise ValueError('Invalid none_policy ' + str(none_policy))
|
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy
:param none_policy:
:param verbose:
:return:
|
entailment
|
def _add_none_handler(validation_callable, # type: Callable
none_policy # type: int
):
# type: (...) -> Callable
"""
Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
:param none_policy: an int representing the None policy, see NonePolicy
:return:
"""
if none_policy is NonePolicy.SKIP:
return _none_accepter(validation_callable) # accept all None values
elif none_policy is NonePolicy.FAIL:
return _none_rejecter(validation_callable) # reject all None values
elif none_policy is NonePolicy.VALIDATE:
return validation_callable # do not handle None specifically, do not wrap
else:
raise ValueError('Invalid none_policy : ' + str(none_policy))
|
Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy
:param validation_callable:
:param none_policy: an int representing the None policy, see NonePolicy
:return:
|
entailment
|
def add_base_type_dynamically(error_type, additional_type):
"""
Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type
(second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names
(fully qualified for the first type, __name__ for the second)
For example
```
> new_type = add_base_type_dynamically(ValidationError, ValueError)
> repr(new_type)
"<class 'valid8.entry_points.ValidationError+ValueError'>"
```
:return:
"""
# the new type created dynamically, with the same name
class new_error_type(with_metaclass(MetaReprForValidator, error_type, additional_type, object)):
pass
new_error_type.__name__ = error_type.__name__ + '[' + additional_type.__name__ + ']'
if sys.version_info >= (3, 0):
new_error_type.__qualname__ = error_type.__qualname__ + '[' + additional_type.__qualname__+ ']'
new_error_type.__module__ = error_type.__module__
return new_error_type
|
Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type
(second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names
(fully qualified for the first type, __name__ for the second)
For example
```
> new_type = add_base_type_dynamically(ValidationError, ValueError)
> repr(new_type)
"<class 'valid8.entry_points.ValidationError+ValueError'>"
```
:return:
|
entailment
|
def assert_valid(name, # type: str
value, # type: Any
*validation_func, # type: ValidationFuncs
**kwargs):
"""
Validates value `value` using validation function(s) `base_validator_s`.
As opposed to `is_valid`, this function raises a `ValidationError` if validation fails.
It is therefore designed to be used for defensive programming, in an independent statement before the code that you
intent to protect.
```python
assert_valid(x, isfinite):
...<your code>
```
Note: this is a friendly alias for `_validator(base_validator_s)(value)`
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param name: the name of the variable to validate. It will be used in error messages
:param value: the value to validate
:param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities.
Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow
the same validation process.
:param error_type: a subclass of ValidationError to raise in case of validation failure. By default a
ValidationError will be raised with the provided help_msg
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error
in case of validation failure
:return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError.
"""
error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None),
('help_msg', None),
('none_policy', None)], allow_others=True)
# the rest of keyword arguments is used as context.
kw_context_args = kwargs
return Validator(*validation_func, error_type=error_type, help_msg=help_msg,
none_policy=none_policy).assert_valid(name=name, value=value, **kw_context_args)
|
Validates value `value` using validation function(s) `base_validator_s`.
As opposed to `is_valid`, this function raises a `ValidationError` if validation fails.
It is therefore designed to be used for defensive programming, in an independent statement before the code that you
intent to protect.
```python
assert_valid(x, isfinite):
...<your code>
```
Note: this is a friendly alias for `_validator(base_validator_s)(value)`
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param name: the name of the variable to validate. It will be used in error messages
:param value: the value to validate
:param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities.
Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow
the same validation process.
:param error_type: a subclass of ValidationError to raise in case of validation failure. By default a
ValidationError will be raised with the provided help_msg
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error
in case of validation failure
:return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError.
|
entailment
|
def is_valid(value,
*validation_func, # type: Union[Callable, List[Callable]]
**kwargs
):
# type: (...) -> bool
"""
Validates value `value` using validation function(s) `validator_func`.
As opposed to `assert_valid`, this function returns a boolean indicating if validation was a success or a failure.
It is therefore designed to be used within if ... else ... statements:
```python
if is_valid(x, isfinite):
...<code>
else
...<code>
```
Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)`
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param value: the value to validate
:param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities.
Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow
the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a
returned value of False
:return: True if validation was a success, False otherwise
"""
none_policy = pop_kwargs(kwargs, [('none_policy', None)])
return Validator(*validation_func, none_policy=none_policy).is_valid(value)
|
Validates value `value` using validation function(s) `validator_func`.
As opposed to `assert_valid`, this function returns a boolean indicating if validation was a success or a failure.
It is therefore designed to be used within if ... else ... statements:
```python
if is_valid(x, isfinite):
...<code>
else
...<code>
```
Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)`
:param validation_func: the base validation function or list of base validation functions to use. A callable, a
tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists
are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit
`_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead
of callables, they will be transformed to functions automatically.
:param value: the value to validate
:param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities.
Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow
the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a
returned value of False
:return: True if validation was a success, False otherwise
|
entailment
|
def create_manually(cls,
validation_function_name, # type: str
var_name, # type: str
var_value,
validation_outcome=None, # type: Any
help_msg=None, # type: str
append_details=True, # type: bool
**kw_context_args):
"""
Creates an instance without using a Validator.
This method is not the primary way that errors are created - they should rather created by the validation entry
points. However it can be handy in rare edge cases.
:param validation_function_name:
:param var_name:
:param var_value:
:param validation_outcome:
:param help_msg:
:param append_details:
:param kw_context_args:
:return:
"""
# create a dummy validator
def val_fun(x):
pass
val_fun.__name__ = validation_function_name
validator = Validator(val_fun, error_type=cls, help_msg=help_msg, **kw_context_args)
# create the exception
# e = cls(validator, var_value, var_name, validation_outcome=validation_outcome, help_msg=help_msg,
# append_details=append_details, **kw_context_args)
e = validator._create_validation_error(var_name, var_value, validation_outcome, error_type=cls,
help_msg=help_msg, **kw_context_args)
return e
|
Creates an instance without using a Validator.
This method is not the primary way that errors are created - they should rather created by the validation entry
points. However it can be handy in rare edge cases.
:param validation_function_name:
:param var_name:
:param var_value:
:param validation_outcome:
:param help_msg:
:param append_details:
:param kw_context_args:
:return:
|
entailment
|
def get_details(self):
""" The function called to get the details appended to the help message when self.append_details is True """
# create the exception main message according to the type of result
if isinstance(self.validation_outcome, Exception):
prefix = 'Validation function [{val}] raised ' if self.display_prefix_for_exc_outcomes else ''
# new: we now remove "Root validator was [{validator}]", users can get it through e.validator
contents = ('Error validating {what}. ' + prefix + '{exception}: {details}')\
.format(what=self.get_what_txt(),
val=self.validator.get_main_function_name(),
exception=type(self.validation_outcome).__name__,
details=end_with_dot(str(self.validation_outcome)))
else:
contents = 'Error validating {what}: validation function [{val}] returned [{result}].' \
''.format(what=self.get_what_txt(), val=self.validator.get_main_function_name(),
result=self.validation_outcome)
# return 'Wrong value: [{}]'.format(self.var_value)
return contents
|
The function called to get the details appended to the help message when self.append_details is True
|
entailment
|
def get_variable_str(self):
"""
Utility method to get the variable value or 'var_name=value' if name is not None.
Note that values with large string representations will not get printed
:return:
"""
if self.var_name is None:
prefix = ''
else:
prefix = self.var_name
suffix = str(self.var_value)
if len(suffix) == 0:
suffix = "''"
elif len(suffix) > self.__max_str_length_displayed__:
suffix = ''
if len(prefix) > 0 and len(suffix) > 0:
return prefix + '=' + suffix
else:
return prefix + suffix
|
Utility method to get the variable value or 'var_name=value' if name is not None.
Note that values with large string representations will not get printed
:return:
|
entailment
|
def assert_valid(self,
name, # type: str
value, # type: Any
error_type=None, # type: Type[ValidationError]
help_msg=None, # type: str
**kw_context_args):
"""
Asserts that the provided named value is valid with respect to the inner base validation functions. It returns
silently in case of success, and raises a `ValidationError` or a subclass in case of failure. This corresponds
to a 'Defensive programming' (sometimes known as 'Offensive programming') mode.
By default this raises instances of `ValidationError` with a default message, in case of failure. There are
two ways that you can customize this behaviour:
* if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created
will be customized with the provided help message.
* if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be
created. Note that you may still provide a `help_msg`.
It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique
error type for each kind of applicative error. This eases the process of error handling at app-level.
:param name: the name of the variable to validate (for error messages)
:param value: the value to validate
:param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a
`ValidationError` will be raised with the provided `help_msg`
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param kw_context_args: optional contextual information to store in the exception, and that may be also used
to format the help message
:return: nothing in case of success. Otherwise, raises a ValidationError
"""
try:
# perform validation
res = self.main_function(value)
except Exception as e:
# caught any exception: raise ValidationError or subclass with that exception in the details
# --old bad idea: first wrap into a failure ==> NO !!! I tried and it was making it far too messy/verbose
# note: we do not have to 'raise x from e' of `raise_from`since the ValidationError constructor already
# sets the __cause__ so we can safely take the same handling than for non-exception failures.
res = e
# check the result
if not result_is_success(res):
raise_(self._create_validation_error(name, value, validation_outcome=res, error_type=error_type,
help_msg=help_msg, **kw_context_args))
|
Asserts that the provided named value is valid with respect to the inner base validation functions. It returns
silently in case of success, and raises a `ValidationError` or a subclass in case of failure. This corresponds
to a 'Defensive programming' (sometimes known as 'Offensive programming') mode.
By default this raises instances of `ValidationError` with a default message, in case of failure. There are
two ways that you can customize this behaviour:
* if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created
will be customized with the provided help message.
* if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be
created. Note that you may still provide a `help_msg`.
It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique
error type for each kind of applicative error. This eases the process of error handling at app-level.
:param name: the name of the variable to validate (for error messages)
:param value: the value to validate
:param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a
`ValidationError` will be raised with the provided `help_msg`
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param kw_context_args: optional contextual information to store in the exception, and that may be also used
to format the help message
:return: nothing in case of success. Otherwise, raises a ValidationError
|
entailment
|
def _create_validation_error(self,
name, # type: str
value, # type: Any
validation_outcome=None, # type: Any
error_type=None, # type: Type[ValidationError]
help_msg=None, # type: str
**kw_context_args):
""" The function doing the final error raising. """
# first merge the info provided in arguments and in self
error_type = error_type or self.error_type
help_msg = help_msg or self.help_msg
ctx = copy(self.kw_context_args)
ctx.update(kw_context_args)
# allow the class to override the name
name = self._get_name_for_errors(name)
if issubclass(error_type, TypeError) or issubclass(error_type, ValueError):
# this is most probably a custom error type, it is already annotated with ValueError and/or TypeError
# so use it 'as is'
new_error_type = error_type
else:
# Add the appropriate TypeError/ValueError base type dynamically
additional_type = None
if isinstance(validation_outcome, Exception):
if is_error_of_type(validation_outcome, TypeError):
additional_type = TypeError
elif is_error_of_type(validation_outcome, ValueError):
additional_type = ValueError
if additional_type is None:
# not much we can do here, let's assume a ValueError, that is more probable
additional_type = ValueError
new_error_type = add_base_type_dynamically(error_type, additional_type)
# then raise the appropriate ValidationError or subclass
return new_error_type(validator=self, var_value=value, var_name=name, validation_outcome=validation_outcome,
help_msg=help_msg, **ctx)
|
The function doing the final error raising.
|
entailment
|
def is_valid(self,
value # type: Any
):
# type: (...) -> bool
"""
Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
the validation process will be silently caught.
:param value: the value to validate
:return: a boolean flag indicating success or failure
"""
# noinspection PyBroadException
try:
# perform validation
res = self.main_function(value)
# return a boolean indicating if success or failure
return result_is_success(res)
except Exception:
# caught exception means failure > return False
return False
|
Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in
the validation process will be silently caught.
:param value: the value to validate
:return: a boolean flag indicating success or failure
|
entailment
|
def create_tags(user):
"""Create a tag."""
values = {
'id': utils.gen_uuid(),
'created_at': datetime.datetime.utcnow().isoformat()
}
values.update(schemas.tag.post(flask.request.json))
with flask.g.db_conn.begin():
where_clause = sql.and_(
_TABLE.c.name == values['name'])
query = sql.select([_TABLE.c.id]).where(where_clause)
if flask.g.db_conn.execute(query).fetchone():
raise dci_exc.DCIConflict('Tag already exists', values)
# create the label/value row
query = _TABLE.insert().values(**values)
flask.g.db_conn.execute(query)
result = json.dumps({'tag': values})
return flask.Response(result, 201,
content_type='application/json')
|
Create a tag.
|
entailment
|
def get_tags(user):
"""Get all tags."""
args = schemas.args(flask.request.args.to_dict())
query = v1_utils.QueryBuilder(_TABLE, args, _T_COLUMNS)
nb_rows = query.get_number_of_rows()
rows = query.execute(fetchall=True)
rows = v1_utils.format_result(rows, _TABLE.name)
return flask.jsonify({'tags': rows, '_meta': {'count': nb_rows}})
|
Get all tags.
|
entailment
|
def delete_tag_by_id(user, tag_id):
"""Delete a tag."""
query = _TABLE.delete().where(_TABLE.c.id == tag_id)
result = flask.g.db_conn.execute(query)
if not result.rowcount:
raise dci_exc.DCIConflict('Tag deletion conflict', tag_id)
return flask.Response(None, 204, content_type='application/json')
|
Delete a tag.
|
entailment
|
def init_app(self, app, entry_point_group='invenio_assets.bundles',
**kwargs):
"""Initialize application object.
:param app: An instance of :class:`~flask.Flask`.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*.
"""
self.init_config(app)
self.env.init_app(app)
self.collect.init_app(app)
self.webpack.init_app(app)
if entry_point_group:
self.load_entrypoint(entry_point_group)
app.extensions['invenio-assets'] = self
|
Initialize application object.
:param app: An instance of :class:`~flask.Flask`.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*.
|
entailment
|
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
app.config.setdefault('REQUIREJS_BASEURL', app.static_folder)
app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder)
app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link')
app.config.setdefault(
'COLLECT_FILTER', partial(collect_staticroot_removal, app))
app.config.setdefault(
'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')
|
Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
|
entailment
|
def load_entrypoint(self, entry_point_group):
"""Load entrypoint.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*.
"""
for ep in pkg_resources.iter_entry_points(entry_point_group):
self.env.register(ep.name, ep.load())
|
Load entrypoint.
:param entry_point_group: A name of entry point group used to load
``webassets`` bundles.
.. versionchanged:: 1.0.0b2
The *entrypoint* has been renamed to *entry_point_group*.
|
entailment
|
def assert_instance_of(value,
allowed_types # type: Union[Type, Tuple[Type]]
):
"""
An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a HasWrongType exception in case of failure.
Used in validate and validation/validator
:param value: the value to check
:param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
match is enough to succeed. If None, type will not be enforced
:return:
"""
if not isinstance(value, allowed_types):
try:
# more than 1 ?
allowed_types[1]
raise HasWrongType(wrong_value=value, ref_type=allowed_types,
help_msg='Value should be an instance of any of {ref_type}')
except IndexError:
# 1
allowed_types = allowed_types[0]
except TypeError:
# 1
pass
raise HasWrongType(wrong_value=value, ref_type=allowed_types)
|
An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a HasWrongType exception in case of failure.
Used in validate and validation/validator
:param value: the value to check
:param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
match is enough to succeed. If None, type will not be enforced
:return:
|
entailment
|
def assert_subclass_of(typ,
allowed_types # type: Union[Type, Tuple[Type]]
):
"""
An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a IsWrongType exception in case of failure.
Used in validate and validation/validator
:param typ: the type to check
:param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types:
one match is enough to succeed. If None, type will not be enforced
:return:
"""
if not issubclass(typ, allowed_types):
try:
# more than 1 ?
allowed_types[1]
raise IsWrongType(wrong_value=typ, ref_type=allowed_types,
help_msg='Value should be a subclass of any of {ref_type}')
except IndexError:
# 1
allowed_types = allowed_types[0]
except TypeError:
# 1
pass
raise IsWrongType(wrong_value=typ, ref_type=allowed_types)
|
An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of
success, and raises a IsWrongType exception in case of failure.
Used in validate and validation/validator
:param typ: the type to check
:param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types:
one match is enough to succeed. If None, type will not be enforced
:return:
|
entailment
|
def validate(name, # type: str
value, # type: Any
enforce_not_none=True, # type: bool
equals=None, # type: Any
instance_of=None, # type: Union[Type, Tuple[Type]]
subclass_of=None, # type: Union[Type, Tuple[Type]]
is_in=None, # type: Container
subset_of=None, # type: Set
contains = None, # type: Union[Any, Iterable]
superset_of=None, # type: Set
min_value=None, # type: Any
min_strict=False, # type: bool
max_value=None, # type: Any
max_strict=False, # type: bool
length=None, # type: int
min_len=None, # type: int
min_len_strict=False, # type: bool
max_len=None, # type: int
max_len_strict=False, # type: bool
custom=None, # type: Callable[[Any], Any]
error_type=None, # type: Type[ValidationError]
help_msg=None, # type: str
**kw_context_args):
"""
A validation function for quick inline validation of `value`, with minimal capabilities:
* None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
* Type validation: `value` should be an instance of any of `var_types` if provided
* Value validation:
* if `allowed_values` is provided, `value` should be in that set
* if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by
default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True`
* if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by
default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True`
:param name: the applicative name of the checked value, that will be used in error messages
:param value: the value to check
:param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None.
:param equals: an optional value to enforce.
:param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
match is enough to succeed. If None, type will not be enforced
:param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
match is enough to succeed. If None, type will not be enforced
:param is_in: an optional set of allowed values.
:param subset_of: an optional superset for the variable
:param contains: an optional value that the variable should contain (value in variable == True)
:param superset_of: an optional subset for the variable
:param min_value: an optional minimum value
:param min_strict: if True, only values strictly greater than `min_value` will be accepted
:param max_value: an optional maximum value
:param max_strict: if True, only values strictly lesser than `max_value` will be accepted
:param length: an optional strict length
:param min_len: an optional minimum length
:param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted
:param max_len: an optional maximum length
:param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted
:param custom: a custom base validation function or list of base validation functions to use. This is the same
syntax than for valid8 decorators. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type),
or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate
an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be
used instead of callables, they will be transformed to functions automatically.
:param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a
`ValidationError` will be raised with the provided `help_msg`
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param kw_context_args: optional contextual information to store in the exception, and that may be also used
to format the help message
:return: nothing in case of success. Otherwise, raises a ValidationError
"""
# backwards compatibility
instance_of = instance_of or (kw_context_args.pop('allowed_types') if 'allowed_types' in kw_context_args else None)
is_in = is_in or (kw_context_args.pop('allowed_values') if 'allowed_values' in kw_context_args else None)
try:
# the following corresponds to an inline version of
# - _none_rejecter in base.py
# - gt/lt in comparables.py
# - is_in/contains/subset_of/superset_of/has_length/minlen/maxlen/is_in in collections.py
# - instance_of/subclass_of in types.py
# try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ?
# > maybe not because quite dangerous (AST mod) and below we skip the "return True" everywhere for performance
#
# Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically
# > but this is not py2 compliant
if value is None:
# inlined version of _none_rejecter in base.py
if enforce_not_none:
raise ValueIsNone(wrong_value=value)
# raise MissingMandatoryParameterException('Error, ' + name + '" is mandatory, it should be non-None')
# else do nothing and return
else:
if equals is not None:
if value != equals:
raise NotEqual(wrong_value=value, ref_value=equals)
if instance_of is not None:
assert_instance_of(value, instance_of)
if subclass_of is not None:
assert_subclass_of(value, subclass_of)
if is_in is not None:
# inlined version of is_in(allowed_values=allowed_values)(value) without 'return True'
if value not in is_in:
raise NotInAllowedValues(wrong_value=value, allowed_values=is_in)
if contains is not None:
# inlined version of contains(ref_value=contains)(value) without 'return True'
if contains not in value:
raise DoesNotContainValue(wrong_value=value, ref_value=contains)
if subset_of is not None:
# inlined version of is_subset(reference_set=subset_of)(value)
missing = value - subset_of
if len(missing) != 0:
raise NotSubset(wrong_value=value, reference_set=subset_of, unsupported=missing)
if superset_of is not None:
# inlined version of is_superset(reference_set=superset_of)(value)
missing = superset_of - value
if len(missing) != 0:
raise NotSuperset(wrong_value=value, reference_set=superset_of, missing=missing)
if min_value is not None:
# inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True'
if min_strict:
if not value > min_value:
raise TooSmall(wrong_value=value, min_value=min_value, strict=True)
else:
if not value >= min_value:
raise TooSmall(wrong_value=value, min_value=min_value, strict=False)
if max_value is not None:
# inlined version of lt(max_value=max_value, strict=max_strict)(value) without 'return True'
if max_strict:
if not value < max_value:
raise TooBig(wrong_value=value, max_value=max_value, strict=True)
else:
if not value <= max_value:
raise TooBig(wrong_value=value, max_value=max_value, strict=False)
if length is not None:
# inlined version of has_length() without 'return True'
if len(value) != length:
raise WrongLength(wrong_value=value, ref_length=length)
if min_len is not None:
# inlined version of minlen(min_length=min_len, strict=min_len_strict)(value) without 'return True'
if min_len_strict:
if not len(value) > min_len:
raise TooShort(wrong_value=value, min_length=min_len, strict=True)
else:
if not len(value) >= min_len:
raise TooShort(wrong_value=value, min_length=min_len, strict=False)
if max_len is not None:
# inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True'
if max_len_strict:
if not len(value) < max_len:
raise TooLong(wrong_value=value, max_length=max_len, strict=True)
else:
if not len(value) <= max_len:
raise TooLong(wrong_value=value, max_length=max_len, strict=False)
except Exception as e:
err = _QUICK_VALIDATOR._create_validation_error(name, value, validation_outcome=e, error_type=error_type,
help_msg=help_msg, **kw_context_args)
raise_(err)
if custom is not None:
# traditional custom validator
assert_valid(name, value, custom, error_type=error_type, help_msg=help_msg, **kw_context_args)
else:
# basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args
if error_type is None and help_msg is None and len(kw_context_args) > 0:
raise ValueError("Keyword context arguments have been provided but help_msg and error_type are not: {}"
"".format(kw_context_args))
|
A validation function for quick inline validation of `value`, with minimal capabilities:
* None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False)
* Type validation: `value` should be an instance of any of `var_types` if provided
* Value validation:
* if `allowed_values` is provided, `value` should be in that set
* if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by
default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True`
* if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by
default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True`
:param name: the applicative name of the checked value, that will be used in error messages
:param value: the value to check
:param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None.
:param equals: an optional value to enforce.
:param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
match is enough to succeed. If None, type will not be enforced
:param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one
match is enough to succeed. If None, type will not be enforced
:param is_in: an optional set of allowed values.
:param subset_of: an optional superset for the variable
:param contains: an optional value that the variable should contain (value in variable == True)
:param superset_of: an optional subset for the variable
:param min_value: an optional minimum value
:param min_strict: if True, only values strictly greater than `min_value` will be accepted
:param max_value: an optional maximum value
:param max_strict: if True, only values strictly lesser than `max_value` will be accepted
:param length: an optional strict length
:param min_len: an optional minimum length
:param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted
:param max_len: an optional maximum length
:param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted
:param custom: a custom base validation function or list of base validation functions to use. This is the same
syntax than for valid8 decorators. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type),
or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate
an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be
used instead of callables, they will be transformed to functions automatically.
:param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a
`ValidationError` will be raised with the provided `help_msg`
:param help_msg: an optional help message to be used in the raised error in case of validation failure.
:param kw_context_args: optional contextual information to store in the exception, and that may be also used
to format the help message
:return: nothing in case of success. Otherwise, raises a ValidationError
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.