本文整理汇总了Python中botocore.exceptions.ParamValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ParamValidationError方法的具体用法?Python exceptions.ParamValidationError怎么用?Python exceptions.ParamValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类botocore.exceptions
的用法示例。
在下文中一共展示了exceptions.ParamValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: crawl_account_hierarchy
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def crawl_account_hierarchy(self):
error_message = f"Unable to crawl AWS organizational structure with ARN {self.account}"
try:
self._init_session()
self._build_accout_alias_map()
self._compute_org_structure_yesterday()
root_ou = self._client.list_roots()["Roots"][0]
LOG.info("Obtained the root identifier: %s" % (root_ou["Id"]))
self._crawl_org_for_accounts(root_ou, root_ou.get("Id"), level=0)
self._mark_nodes_deleted()
except ParamValidationError as param_error:
LOG.warn(msg=error_message)
LOG.warn(param_error)
except ClientError as boto_error:
LOG.warn(msg=error_message, exc_info=boto_error)
except Exception as unknown_error:
LOG.exception(msg=error_message, exc_info=unknown_error)
示例2: validate_parameters
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def validate_parameters(params, shape):
"""Validates input parameters against a schema.
This is a convenience function that validates parameters against a schema.
You can also instantiate and use the ParamValidator class directly if you
want more control.
If there are any validation errors then a ParamValidationError
will be raised. If there are no validation errors than no exception
is raised and a value of None is returned.
:param params: The user provided input parameters.
:type shape: botocore.model.Shape
:param shape: The schema which the input parameters should
adhere to.
:raise: ParamValidationError
"""
validator = ParamValidator()
report = validator.validate(params, shape)
if report.has_errors():
raise ParamValidationError(report=report.generate_report())
示例3: retry
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def retry(attempts=3):
def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
tries = attempts
while True:
tries -= 1
try:
return func(*args, **kwargs)
except (ClientError, ParamValidationError) as error:
if tries > 0:
print('[ssha] {}'.format(error))
else:
raise
return wrapped
return wrapper
示例4: _process_ioc_values
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def _process_ioc_values(self, potential_iocs):
"""Check if any info is malicious by querying DynamoDB IOC table
Args:
potential_iocs (list<str>): A list of potential IOC values
"""
LOGGER.debug('Checking %d potential IOCs for validity', len(potential_iocs))
# Segment data before calling DynamoDB table with batch_get_item.
for query_values in self._segment(potential_iocs):
try:
query_result = self._query(query_values)
except (ClientError, ParamValidationError):
LOGGER.exception('An error occurred while querying dynamodb table')
continue
for ioc in query_result:
yield ioc
示例5: start_query_execution
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def start_query_execution(self, db, query):
try:
if not db:
raise ValueError('Schema must be specified when session schema is not set')
result_configuration = {
'OutputLocation': self.bucket,
}
if self.encryption:
result_configuration['EncryptionConfiguration'] = {
'EncryptionOption': 'SSE_S3'
}
return self.athena.start_query_execution(
QueryString=query,
ClientRequestToken=str(uuid.uuid4()),
QueryExecutionContext={
'Database': db
},
ResultConfiguration=result_configuration
)['QueryExecutionId']
except (ClientError, ParamValidationError, ValueError) as e:
print(e)
return
示例6: can_retry
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def can_retry(self, ex):
"""
Tests if a retry can be done based on the exception of an earlier call
:param ex: Execution raise by earlier call of the boto3 method
:return: True if any of the call_retry_strategy returns True, else False
"""
if type(ex) == ParamValidationError:
return False
return AwsApiServiceRetry.can_retry(self, ex)
示例7: _validate_connector_args
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def _validate_connector_args(connector_args):
if connector_args is None:
return
for k, v in connector_args.items():
# verify_ssl is handled by verify parameter to create_client
if k == 'use_dns_cache':
if not isinstance(v, bool):
raise ParamValidationError(
report='{} value must be a boolean'.format(k))
elif k in ['keepalive_timeout']:
if not isinstance(v, (float, int)):
raise ParamValidationError(
report='{} value must be a float/int'.format(k))
elif k == 'force_close':
if not isinstance(v, bool):
raise ParamValidationError(
report='{} value must be a boolean'.format(k))
# limit is handled by max_pool_connections
elif k == 'ssl_context':
import ssl
if not isinstance(v, ssl.SSLContext):
raise ParamValidationError(
report='{} must be an SSLContext instance'.format(k))
else:
raise ParamValidationError(
report='invalid connector_arg:{}'.format(k))
示例8: test_connector_args
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def test_connector_args():
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(use_dns_cache=1)
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(keepalive_timeout="1")
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(force_close="1")
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# wrong type
connector_args = dict(ssl_context="1")
AioConfig(connector_args)
with pytest.raises(ParamValidationError):
# invalid key
connector_args = dict(foo="1")
AioConfig(connector_args)
# test merge
cfg = Config(read_timeout=75)
aio_cfg = AioConfig({'keepalive_timeout': 75})
aio_cfg.merge(cfg)
assert cfg.read_timeout == 75
assert aio_cfg.connector_args['keepalive_timeout'] == 75
示例9: _get_sts_access
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def _get_sts_access(provider_resource_name):
"""Get for sts access."""
# create an STS client
sts_client = boto3.client("sts")
credentials = dict()
error_message = f"Unable to assume role with ARN {provider_resource_name}."
try:
# Call the assume_role method of the STSConnection object and pass the role
# ARN and a role session name.
assumed_role = sts_client.assume_role(RoleArn=provider_resource_name, RoleSessionName="AccountCreationSession")
credentials = assumed_role.get("Credentials")
except ParamValidationError as param_error:
LOG.warn(msg=error_message)
LOG.info(param_error)
# We can't use the exc_info here because it will print
# a traceback that gets picked up by sentry:
# https://github.com/project-koku/koku/issues/1483
except (ClientError, BotoConnectionError, NoCredentialsError) as boto_error:
LOG.warn(msg=error_message, exc_info=boto_error)
# return a kwargs-friendly format
return dict(
aws_access_key_id=credentials.get("AccessKeyId"),
aws_secret_access_key=credentials.get("SecretAccessKey"),
aws_session_token=credentials.get("SessionToken"),
)
示例10: test_parm_val_exception
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def test_parm_val_exception(self, mock_boto3_client):
"""Test _get_sts_access fail."""
logging.disable(logging.NOTSET)
sts_client = Mock()
sts_client.assume_role.side_effect = ParamValidationError(report="test")
mock_boto3_client.return_value = sts_client
iam_arn = "BAD"
with self.assertLogs(level=logging.CRITICAL):
credentials = _get_sts_access(iam_arn)
self.assertIn("aws_access_key_id", credentials)
self.assertIn("aws_secret_access_key", credentials)
self.assertIn("aws_session_token", credentials)
self.assertIsNone(credentials.get("aws_access_key_id"))
self.assertIsNone(credentials.get("aws_secret_access_key"))
self.assertIsNone(credentials.get("aws_session_token"))
示例11: test_crawl_boto_param_exception
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def test_crawl_boto_param_exception(self, mock_session):
"""Test botocore parameter exception is caught properly."""
logging.disable(logging.NOTSET)
mock_session.client = MagicMock()
unit_crawler = AWSOrgUnitCrawler(self.account)
unit_crawler._init_session()
unit_crawler._client.list_roots.side_effect = ParamValidationError(report="Bad Param")
with self.assertLogs(logger=crawler_log, level=logging.WARNING):
unit_crawler.crawl_account_hierarchy()
示例12: serialize_to_request
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def serialize_to_request(self, parameters, operation_model):
input_shape = operation_model.input_shape
if input_shape is not None:
report = self._param_validator.validate(parameters,
operation_model.input_shape)
if report.has_errors():
raise ParamValidationError(report=report.generate_report())
return self._serializer.serialize_to_request(parameters,
operation_model)
示例13: validate_bucket_name
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def validate_bucket_name(params, **kwargs):
if 'Bucket' not in params:
return
bucket = params['Bucket']
if VALID_BUCKET.search(bucket) is None:
error_msg = (
'Invalid bucket name "%s": Bucket name must match '
'the regex "%s"' % (bucket, VALID_BUCKET.pattern))
raise ParamValidationError(report=error_msg)
示例14: _quote_source_header_from_dict
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def _quote_source_header_from_dict(source_dict):
try:
bucket = source_dict['Bucket']
key = percent_encode(source_dict['Key'], safe=SAFE_CHARS + '/')
version_id = source_dict.get('VersionId')
except KeyError as e:
raise ParamValidationError(
report='Missing required parameter: %s' % str(e))
final = '%s/%s' % (bucket, key)
if version_id is not None:
final += '?versionId=%s' % version_id
return final
示例15: validate_ascii_metadata
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ParamValidationError [as 别名]
def validate_ascii_metadata(params, **kwargs):
"""Verify S3 Metadata only contains ascii characters.
From: http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
"Amazon S3 stores user-defined metadata in lowercase. Each name, value pair
must conform to US-ASCII when using REST and UTF-8 when using SOAP or
browser-based uploads via POST."
"""
metadata = params.get('Metadata')
if not metadata or not isinstance(metadata, dict):
# We have to at least type check the metadata as a dict type
# because this handler is called before param validation.
# We'll go ahead and return because the param validator will
# give a descriptive error message for us.
# We might need a post-param validation event.
return
for key, value in metadata.items():
try:
key.encode('ascii')
value.encode('ascii')
except UnicodeEncodeError as e:
error_msg = (
'Non ascii characters found in S3 metadata '
'for key "%s", value: "%s". \nS3 metadata can only '
'contain ASCII characters. ' % (key, value)
)
raise ParamValidationError(
report=error_msg)