本文整理汇总了Python中click.exceptions.ClickException方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ClickException方法的具体用法?Python exceptions.ClickException怎么用?Python exceptions.ClickException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类click.exceptions
的用法示例。
在下文中一共展示了exceptions.ClickException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initialize
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def initialize(self, base_dir):
if self.skey:
logger.info('Initializing the shodan api.')
result = os.system('shodan init {skey}'.format(skey=self.skey))
if result:
logger.warning('Initializ failed, please check your key.')
return False
self.conf.set("shodan", "shodan_key", self.skey)
self.conf.write(open(base_dir + "/key.ini", "w"))
self.api = Shodan(get_api_key())
else:
from click.exceptions import ClickException
try:
key = None if get_api_key() == '' else get_api_key()
if key:
self.api = Shodan(key)
else:
return False
except ClickException as e:
logger.warning('The shodan api is empty so you can not use shodan api.')
return False
return True
示例2: main
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def main(file: _FilePath, *,
probe: bool = True, probe_retries: int = PROBE_RETRIES_DEFAULT, probe_delay: float = PROBE_DELAY_DEFAULT,
probe_fail_fast: bool = False,
verbose: bool = False
) -> None: # pragma: no cover
_print_if(verbose, '* VALIDATING...')
try:
config = parse_yaml_file(file)
except Exception as ex:
_log('debug', 'Error during config parse.', exc_info=ex)
raise ClickException(f'ValidationError: {ex}') from ex
_print_if(verbose, f'Config: {config!r}')
check_config(config)
if probe:
_print_if(verbose, '* PROBING...')
probe_config(config, retries=probe_retries, delay=probe_delay, fail_fast=probe_fail_fast, verbose=verbose)
示例3: probe_config
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def probe_config(config: Config, *,
retries: int, delay: float,
fail_fast: bool = False,
verbose: bool = False) -> None: # pragma: no cover
# TODO implement a progress bar ?
config_probe_start = time()
config_probe_results = ConfigTest(config).probe(
delay=delay, retries=retries,
callback=make_probe_status_callback(fail_fast=fail_fast, verbose=verbose))
config_probe_end = time()
if verbose:
print_probed_erroneous(config_probe_results)
print_probed_summary(config_probe_results, elapsed_seconds=config_probe_end - config_probe_start)
failed_imagecrawlers = [
probed.imagecrawler
for probed
in config_probe_results # pylint: disable=not-an-iterable
if probed.result.is_failure
]
if failed_imagecrawlers:
raise ClickException('ProbeError(s) occurred for:\n\t' + '\n\t'.join(map(str, failed_imagecrawlers)))
示例4: test_load_extended_settings
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def test_load_extended_settings(self):
zappa_cli = ZappaCLI()
zappa_cli.api_stage = 'extendo'
zappa_cli.load_settings('test_settings.json')
self.assertEqual('lmbda', zappa_cli.stage_config['s3_bucket'])
self.assertEqual(True, zappa_cli.stage_config['touch'])
zappa_cli = ZappaCLI()
zappa_cli.api_stage = 'extendofail'
with self.assertRaises(ClickException):
zappa_cli.load_settings('test_settings.json')
zappa_cli = ZappaCLI()
zappa_cli.api_stage = 'ttt888'
with self.assertRaises(RuntimeError):
zappa_cli.load_settings('tests/test_bad_circular_extends_settings.json')
zappa_cli = ZappaCLI()
zappa_cli.api_stage = 'extendo2'
zappa_cli.load_settings('test_settings.json')
self.assertEqual('lmbda2', zappa_cli.stage_config['s3_bucket']) # Second Extension
self.assertTrue(zappa_cli.stage_config['touch']) # First Extension
self.assertTrue(zappa_cli.stage_config['delete_local_zip']) # The base
示例5: check_config
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def check_config(config: Config) -> None: # pragma: no cover
try:
ConfigTest(config).check_duplicates()
except Exception as ex:
_log('debug', 'Error during config check.', exc_info=ex)
raise ClickException(f'ValidationError: {ex}') from ex
示例6: stage_config
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def stage_config(self):
"""
A shortcut property for settings of a stage.
"""
def get_stage_setting(stage, extended_stages=None):
if extended_stages is None:
extended_stages = []
if stage in extended_stages:
raise RuntimeError(stage + " has already been extended to these settings. "
"There is a circular extends within the settings file.")
extended_stages.append(stage)
try:
stage_settings = dict(self.zappa_settings[stage].copy())
except KeyError:
raise ClickException("Cannot extend settings for undefined stage '" + stage + "'.")
extends_stage = self.zappa_settings[stage].get('extends', None)
if not extends_stage:
return stage_settings
extended_settings = get_stage_setting(stage=extends_stage, extended_stages=extended_stages)
extended_settings.update(stage_settings)
return extended_settings
settings = get_stage_setting(stage=self.api_stage)
# Backwards compatible for delete_zip setting that was more explicitly named delete_local_zip
if 'delete_zip' in settings:
settings['delete_local_zip'] = settings.get('delete_zip')
settings.update(self.stage_config_overrides)
return settings
示例7: template
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def template(self, lambda_arn, role_arn, output=None, json=False):
"""
Only build the template file.
"""
if not lambda_arn:
raise ClickException("Lambda ARN is required to template.")
if not role_arn:
raise ClickException("Role ARN is required to template.")
self.zappa.credentials_arn = role_arn
# Create the template!
template = self.zappa.create_stack_template(
lambda_arn=lambda_arn,
lambda_name=self.lambda_name,
api_key_required=self.api_key_required,
iam_authorization=self.iam_authorization,
authorizer=self.authorizer,
cors_options=self.cors,
description=self.apigateway_description,
endpoint_configuration=self.endpoint_configuration
)
if not output:
template_file = self.lambda_name + '-template-' + str(int(time.time())) + '.json'
else:
template_file = output
with open(template_file, 'wb') as out:
out.write(bytes(template.to_json(indent=None, separators=(',',':')), "utf-8"))
if not json:
click.echo(click.style("Template created", fg="green", bold=True) + ": " + click.style(template_file, bold=True))
else:
with open(template_file, 'r') as out:
print(out.read())
示例8: unschedule
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def unschedule(self):
"""
Given a a list of scheduled functions,
tear down their regular execution.
"""
# Run even if events are not defined to remove previously existing ones (thus default to []).
events = self.stage_config.get('events', [])
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return
function_arn = None
try:
function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
function_arn = function_response['Configuration']['FunctionArn']
except botocore.exceptions.ClientError as e: # pragma: no cover
raise ClickException("Function does not exist, you should deploy first. Ex: zappa deploy {}. "
"Proceeding to unschedule CloudWatch based events.".format(self.api_stage))
print("Unscheduling..")
self.zappa.unschedule_events(
lambda_name=self.lambda_name,
lambda_arn=function_arn,
events=events,
)
# Remove async task SNS
if self.stage_config.get('async_source', None) == 'sns' \
and self.stage_config.get('async_resources', True):
removed_arns = self.zappa.remove_async_sns_topic(self.lambda_name)
click.echo('SNS Topic removed: %s' % ', '.join(removed_arns))
示例9: get_json_or_yaml_settings
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def get_json_or_yaml_settings(self, settings_name="zappa_settings"):
"""
Return zappa_settings path as JSON or YAML (or TOML), as appropriate.
"""
zs_json = settings_name + ".json"
zs_yml = settings_name + ".yml"
zs_yaml = settings_name + ".yaml"
zs_toml = settings_name + ".toml"
# Must have at least one
if not os.path.isfile(zs_json) \
and not os.path.isfile(zs_yml) \
and not os.path.isfile(zs_yaml) \
and not os.path.isfile(zs_toml):
raise ClickException("Please configure a zappa_settings file or call `zappa init`.")
# Prefer JSON
if os.path.isfile(zs_json):
settings_file = zs_json
elif os.path.isfile(zs_toml):
settings_file = zs_toml
elif os.path.isfile(zs_yml):
settings_file = zs_yml
else:
settings_file = zs_yaml
return settings_file
示例10: load_settings_file
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def load_settings_file(self, settings_file=None):
"""
Load our settings file.
"""
if not settings_file:
settings_file = self.get_json_or_yaml_settings()
if not os.path.isfile(settings_file):
raise ClickException("Please configure your zappa_settings file or call `zappa init`.")
path, ext = os.path.splitext(settings_file)
if ext == '.yml' or ext == '.yaml':
with open(settings_file) as yaml_file:
try:
self.zappa_settings = yaml.safe_load(yaml_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings YAML. It may be malformed.")
elif ext == '.toml':
with open(settings_file) as toml_file:
try:
self.zappa_settings = toml.load(toml_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings TOML. It may be malformed.")
else:
with open(settings_file) as json_file:
try:
self.zappa_settings = json.load(json_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings JSON. It may be malformed.")
示例11: execute_prebuild_script
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def execute_prebuild_script(self):
"""
Parse and execute the prebuild_script from the zappa_settings.
"""
(pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1)
try: # Prefer prebuild script in working directory
if pb_mod_path.count('.') >= 1: # Prebuild script func is nested in a folder
(mod_folder_path, mod_name) = pb_mod_path.rsplit('.', 1)
mod_folder_path_fragments = mod_folder_path.split('.')
working_dir = os.path.join(os.getcwd(), *mod_folder_path_fragments)
else:
mod_name = pb_mod_path
working_dir = os.getcwd()
working_dir_importer = pkgutil.get_importer(working_dir)
module_ = working_dir_importer.find_module(mod_name).load_module(mod_name)
except (ImportError, AttributeError):
try: # Prebuild func might be in virtualenv
module_ = importlib.import_module(pb_mod_path)
except ImportError: # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"import prebuild script ", bold=True) + 'module: "{pb_mod_path}"'.format(
pb_mod_path=click.style(pb_mod_path, bold=True)))
if not hasattr(module_, pb_func): # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"find prebuild script ", bold=True) + 'function: "{pb_func}" '.format(
pb_func=click.style(pb_func, bold=True)) + 'in module "{pb_mod_path}"'.format(
pb_mod_path=pb_mod_path))
prebuild_function = getattr(module_, pb_func)
prebuild_function() # Call the function
示例12: check_venv
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def check_venv(self):
""" Ensure we're inside a virtualenv. """
if self.vargs and self.vargs.get("no_venv"):
return
if self.zappa:
venv = self.zappa.get_current_venv()
else:
# Just for `init`, when we don't have settings yet.
venv = Zappa.get_current_venv()
if not venv:
raise ClickException(
click.style("Zappa", bold=True) + " requires an " + click.style("active virtual environment", bold=True, fg="red") + "!\n" +
"Learn more about virtual environments here: " + click.style("http://docs.python-guide.org/en/latest/dev/virtualenvs/", bold=False, fg="cyan"))
示例13: get_command
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def get_command(self, ctx, name):
"""Imports the command if available in commmands list and provides with
most similar commands if the command is not present in the list.
Args:
name(str): The name of the command.
Returns:
click.core.Command: It is a new command and uses the decorated
function as callback.For reference visit
https://click.palletsprojects.com/en/7.x/api/#decorators .
"""
try:
if sys.version_info[0] == 2:
name = name.encode("ascii", "replace")
mod = __import__("popper.commands.cmd_" + name, None, None, ["cli"])
except ImportError as e:
commands = self.list_commands(ctx)
most_similar_commands = ", ".join(
difflib.get_close_matches(name, commands, 3, 0.3)
)
message = ""
if len(most_similar_commands) != 0:
message = "\n\nThe most similar commands are: " + most_similar_commands
raise ClickException(
"Command '" + name + "' doesn't exist.\n"
"Type 'popper --help' for more.\n" + message + "\n" + str(e)
)
return mod.cli
示例14: test_check_size
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def test_check_size(self):
result = disk_check_size(None, None, 2048)
self.assertEqual(result, 2048)
self.assertRaises(ClickException, disk_check_size, None, None, 2040)
示例15: test_settings_extension
# 需要导入模块: from click import exceptions [as 别名]
# 或者: from click.exceptions import ClickException [as 别名]
def test_settings_extension(self):
"""
Make sure Zappa uses settings in the proper order: JSON, TOML, YAML.
"""
tempdir = tempfile.mkdtemp(prefix="zappa-test-settings")
shutil.copy("tests/test_one_env.json", tempdir + "/zappa_settings.json")
shutil.copy("tests/test_settings.yml", tempdir + "/zappa_settings.yml")
shutil.copy("tests/test_settings.yml", tempdir + "/zappa_settings.yaml")
shutil.copy("tests/test_settings.toml", tempdir + "/zappa_settings.toml")
orig_cwd = os.getcwd()
os.chdir(tempdir)
try:
zappa_cli = ZappaCLI()
# With all three, we should get the JSON file first.
self.assertEqual(zappa_cli.get_json_or_yaml_settings(),
"zappa_settings.json")
zappa_cli.load_settings_file()
self.assertIn("lonely", zappa_cli.zappa_settings)
os.unlink("zappa_settings.json")
# Without the JSON file, we should get the TOML file.
self.assertEqual(zappa_cli.get_json_or_yaml_settings(),
"zappa_settings.toml")
zappa_cli.load_settings_file()
self.assertIn("ttt888", zappa_cli.zappa_settings)
self.assertNotIn("devor", zappa_cli.zappa_settings)
os.unlink("zappa_settings.toml")
# With just the YAML file, we should get it.
self.assertEqual(zappa_cli.get_json_or_yaml_settings(),
"zappa_settings.yml")
zappa_cli.load_settings_file()
self.assertIn("ttt888", zappa_cli.zappa_settings)
self.assertIn("devor", zappa_cli.zappa_settings)
os.unlink("zappa_settings.yml")
self.assertEqual(zappa_cli.get_json_or_yaml_settings(),
"zappa_settings.yaml")
zappa_cli.load_settings_file()
self.assertIn("ttt888", zappa_cli.zappa_settings)
self.assertIn("devor", zappa_cli.zappa_settings)
os.unlink("zappa_settings.yaml")
# Without anything, we should get an exception.
self.assertRaises(
ClickException, zappa_cli.get_json_or_yaml_settings)
finally:
os.chdir(orig_cwd)
shutil.rmtree(tempdir)