本文整理匯總了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')