本文整理汇总了Python中prompt_toolkit.validation.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python validation.ValidationError方法的具体用法?Python validation.ValidationError怎么用?Python validation.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prompt_toolkit.validation
的用法示例。
在下文中一共展示了validation.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_validator
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def build_validator(validate: Any) -> Optional[Validator]:
if validate:
if inspect.isclass(validate) and issubclass(validate, Validator):
return validate()
elif isinstance(validate, Validator):
return validate
elif callable(validate):
class _InputValidator(Validator):
def validate(self, document):
verdict = validate(document.text)
if verdict is not True:
if verdict is False:
verdict = "invalid input"
raise ValidationError(
message=verdict, cursor_position=len(document.text)
)
return _InputValidator()
return None
示例2: setup_validator
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def setup_validator(kwargs):
# this is an internal helper not meant for public consumption!
# note this works on a dictionary
validate_prompt = kwargs.pop('validate', None)
if validate_prompt:
if issubclass(validate_prompt, Validator):
kwargs['validator'] = validate_prompt()
elif callable(validate_prompt):
class _InputValidator(Validator):
def validate(self, document):
#print('validation!!')
verdict = validate_prompt(document.text)
if isinstance(verdict, basestring):
raise ValidationError(
message=verdict,
cursor_position=len(document.text))
elif verdict is not True:
raise ValidationError(
message='invalid input',
cursor_position=len(document.text))
kwargs['validator'] = _InputValidator()
return kwargs['validator']
示例3: validate
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def validate(self, document):
text = document.text
if not text:
raise ValidationError(message="Please supply a value")
if text.isdigit():
value = int(text)
else:
i = 0
raise ValidationError(
message='Please enter an integer.'
)
if self.minimum and value < self.minimum:
raise ValidationError(
message="Value must be greater than %s" %(self.minimum)
)
if self.maximum and value > self.maximum:
raise ValidationError(
message="Value must be less than %s" %(self.maximum)
)
示例4: validate
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def validate(self, document):
text = document.text.split()
if re.search(r"^(!|#|\?)", document.text):
pass
elif len(text) > 1:
if not text[-2].startswith("--"):
if (
not re.search(r"\"|'", text[-1])
and not text[-1].startswith("--")
and text[-1] not in list(get_options().keys())
):
raise ValidationError(
cursor_position=1,
message="{text} is not a valid Chepy method".format(
text=text[-1]
),
)
示例5: create_validator
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def create_validator(
function: Callable[[Text], bool], error_message: Text
) -> Type["Validator"]:
"""Helper method to create `Validator` classes from callable functions. Should be
removed when questionary supports `Validator` objects."""
from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit.document import Document
class FunctionValidator(Validator):
@staticmethod
def validate(document: Document) -> None:
is_valid = function(document.text)
if not is_valid:
raise ValidationError(message=error_message)
return FunctionValidator
示例6: test_create_validator_from_callable
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def test_create_validator_from_callable():
def is_valid(user_input) -> None:
return user_input == "this passes"
error_message = "try again"
validator = io_utils.create_validator(is_valid, error_message)
document = Document("this passes")
assert validator.validate(document) is None
document = Document("this doesn't")
with pytest.raises(ValidationError) as e:
validator.validate(document)
assert e.value.message == error_message
示例7: validate
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def validate(self, document):
NullValidator.validate(self, document)
text = document.text
if self.allow_quit and text.lower() == 'q':
return
if not text.isdigit():
i = 0
for i, c in enumerate(text):
if not c.isdigit():
break
raise ValidationError(message=self.message, cursor_position=i)
if not bool(self.max_number):
return
valid = int(text) <= int(self.max_number) and not int(text) == 0
if not valid:
range_message = 'You must enter a number between 1 and {}'.format(self.max_number)
raise ValidationError(message=range_message)
示例8: validate
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def validate(self, document: Document) -> None:
if len(document.text) == 0:
raise ValidationError(message="This field is required")
if self.proxy:
return self.proxy.validate(document)
示例9: test_validator_bool_function_fails
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def test_validator_bool_function_fails():
def validate(t):
return len(t) == 3
validator = build_validator(validate)
with pytest.raises(ValidationError) as e:
validator.validate(Document("fooooo"))
assert e.value.message == "invalid input"
示例10: test_validator_instance_fails
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def test_validator_instance_fails():
def validate(t):
return len(t) == 3
validator = Validator.from_callable(validate, error_message="invalid input")
with pytest.raises(ValidationError) as e:
validator.validate(Document("fooooo"))
assert e.value.message == "invalid input"
示例11: test_text_validate_with_class
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def test_text_validate_with_class():
class SimpleValidator(Validator):
def validate(self, document):
ok = re.match("[01][01][01]", document.text)
if not ok:
raise ValidationError(
message="Binary FTW", cursor_position=len(document.text)
)
message = "What is your name"
text = "001\r"
result, cli = feed_cli_with_input("text", message, text, validate=SimpleValidator)
assert result == "001"
示例12: question
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def question(message, **kwargs):
default = kwargs.pop('default', '')
validate_prompt = kwargs.pop('validate', None)
if validate_prompt:
if inspect.isclass(validate_prompt) and issubclass(validate_prompt, Validator):
kwargs['validator'] = validate_prompt()
elif callable(validate_prompt):
class _InputValidator(Validator):
def validate(self, document):
verdict = validate_prompt(document.text)
if not verdict == True:
if verdict == False:
verdict = 'invalid input'
raise ValidationError(
message=verdict,
cursor_position=len(document.text))
kwargs['validator'] = _InputValidator()
# TODO style defaults on detail level
kwargs['style'] = kwargs.pop('style', default_style)
qmark = kwargs.pop('qmark', '?')
def _get_prompt_tokens(cli):
return [
(Token.QuestionMark, qmark),
(Token.Question, ' %s ' % message)
]
return create_prompt_application(
get_prompt_tokens=_get_prompt_tokens,
lexer=SimpleLexer(Token.Answer),
default=default,
**kwargs
)
示例13: setup_simple_validator
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def setup_simple_validator(kwargs):
# this is an internal helper not meant for public consumption!
# note this works on a dictionary
# this validates the answer not a buffer
# TODO
# not sure yet how to deal with the validation result:
# https://github.com/jonathanslenders/python-prompt-toolkit/issues/430
validate = kwargs.pop('validate', None)
if validate is None:
def _always(answer):
return True
return _always
elif not callable(validate):
raise ValueError('Here a simple validate function is expected, no class')
def _validator(answer):
verdict = validate(answer)
if isinstance(verdict, basestring):
raise ValidationError(
message=verdict
)
elif verdict is not True:
raise ValidationError(
message='invalid input'
)
return _validator
# FIXME style defaults on detail level
示例14: validate
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def validate(self, document):
"""
Check input for Python syntax errors.
"""
# When the input starts with Ctrl-Z, always accept. This means EOF in a
# Python REPL.
if document.text.startswith("\x1a"):
return
try:
if self.get_compiler_flags:
flags = self.get_compiler_flags()
else:
flags = 0
compile(document.text, "<input>", "exec", flags=flags, dont_inherit=True)
except SyntaxError as e:
# Note, the 'or 1' for offset is required because Python 2.7
# gives `None` as offset in case of '4=4' as input. (Looks like
# fixed in Python 3.)
index = document.translate_row_col_to_index(
e.lineno - 1, (e.offset or 1) - 1
)
raise ValidationError(index, "Syntax Error")
except TypeError as e:
# e.g. "compile() expected string without null bytes"
raise ValidationError(0, str(e))
except ValueError as e:
# In Python 2, compiling "\x9" (an invalid escape sequence) raises
# ValueError instead of SyntaxError.
raise ValidationError(0, "Syntax Error: %s" % e)
示例15: validate
# 需要导入模块: from prompt_toolkit import validation [as 别名]
# 或者: from prompt_toolkit.validation import ValidationError [as 别名]
def validate(self, document):
text = document.text.strip()
if len(text) == 0:
raise ValidationError(message='Empty input is not allowed')