当前位置: 首页>>代码示例>>Python>>正文


Python client.ClientError方法代码示例

本文整理汇总了Python中botocore.client.ClientError方法的典型用法代码示例。如果您正苦于以下问题:Python client.ClientError方法的具体用法?Python client.ClientError怎么用?Python client.ClientError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在botocore.client的用法示例。


在下文中一共展示了client.ClientError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getMediaConvertJob

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def getMediaConvertJob(id, JOBTABLE):
    """
    Retrieve a job data structure from dynamodb
    :param id:  id of the job
    :param JOBTABLE: Name of the dynamodb job table for this stack
    """    
    try:
        table = DYNAMO_CLIENT.Table(JOBTABLE)
        response = table.get_item(Key={'id': id}, ConsistentRead=True)
    
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        if 'Item' not in response:
            return None
        else:
            item = response['Item']
            print("GetItem succeeded:")
            #print(json.dumps(item, indent=4, cls=DecimalEncoder))
            return item 
开发者ID:aws-samples,项目名称:aws-media-services-vod-automation,代码行数:22,代码来源:event_collector.py

示例2: test_model_subclass_attributes_inherited_on_create

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def test_model_subclass_attributes_inherited_on_create(self):
        scope_args = {'count': 0}

        def fake_dynamodb(*args, **kwargs):
            if scope_args['count'] == 0:
                scope_args['count'] += 1
                raise ClientError({'Error': {'Code': 'ResourceNotFoundException', 'Message': 'Not Found'}},
                                  "DescribeTable")
            return {}

        fake_db = MagicMock()
        fake_db.side_effect = fake_dynamodb

        with patch(PATCH_METHOD, new=fake_db) as req:
            Dog.create_table(read_capacity_units=2, write_capacity_units=2)

            actual = req.call_args_list[1][0][1]

            self.assertEqual(actual['TableName'], DOG_TABLE_DATA['Table']['TableName'])
            self.assert_dict_lists_equal(actual['KeySchema'], DOG_TABLE_DATA['Table']['KeySchema'])
            self.assert_dict_lists_equal(actual['AttributeDefinitions'],
                                         DOG_TABLE_DATA['Table']['AttributeDefinitions']) 
开发者ID:pynamodb,项目名称:PynamoDB,代码行数:24,代码来源:test_model.py

示例3: test_describe_table

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def test_describe_table(self):
        """
        Connection.describe_table
        """
        with patch(PATCH_METHOD) as req:
            req.return_value = DESCRIBE_TABLE_DATA
            conn = Connection(self.region)
            conn.describe_table(self.test_table_name)
            self.assertEqual(req.call_args[0][1], {'TableName': 'ci-table'})

        with self.assertRaises(TableDoesNotExist):
            with patch(PATCH_METHOD) as req:
                req.side_effect = ClientError({'Error': {'Code': 'ResourceNotFoundException', 'Message': 'Not Found'}}, "DescribeTable")
                conn = Connection(self.region)
                conn.describe_table(self.test_table_name)

        with self.assertRaises(TableDoesNotExist):
            with patch(PATCH_METHOD) as req:
                req.side_effect = ValueError()
                conn = Connection(self.region)
                conn.describe_table(self.test_table_name) 
开发者ID:pynamodb,项目名称:PynamoDB,代码行数:23,代码来源:test_base_connection.py

示例4: test_make_api_call_throws_verbose_error_after_backoff

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def test_make_api_call_throws_verbose_error_after_backoff(self, client_mock):
        response = AWSResponse(
            url='http://lyft.com',
            status_code=500,
            raw='',  # todo: use stream, like `botocore.tests.RawResponse`?
            headers={'x-amzn-RequestId': 'abcdef'},
        )
        response._content = json.dumps({'message': 'There is a problem', '__type': 'InternalServerError'}).encode('utf-8')
        client_mock._endpoint.http_session.send.return_value = response

        c = Connection()

        with self.assertRaises(ClientError):
            try:
                c._make_api_call('CreateTable', {'TableName': 'MyTable'})
            except Exception as e:
                self.assertEqual(
                    str(e),
                    'An error occurred (InternalServerError) on request (abcdef) on table (MyTable) when calling the CreateTable operation: There is a problem'
                )
                raise 
开发者ID:pynamodb,项目名称:PynamoDB,代码行数:23,代码来源:test_base_connection.py

示例5: role

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def role():
    new_role = False
    try:
        logger.info('finding role')
        iam('get_role', RoleName='gimel')
    except ClientError:
        logger.info('role not found. creating')
        iam('create_role', RoleName='gimel',
            AssumeRolePolicyDocument=ASSUMED_ROLE_POLICY)
        new_role = True

    role_arn = iam('get_role', RoleName='gimel', query='Role.Arn')
    logger.debug('role_arn={}'.format(role_arn))

    logger.info('updating role policy')

    iam('put_role_policy', RoleName='gimel', PolicyName='gimel',
        PolicyDocument=POLICY)

    if new_role:
        from time import sleep
        logger.info('waiting for role policy propagation')
        sleep(5)

    return role_arn 
开发者ID:Alephbet,项目名称:gimel,代码行数:27,代码来源:deploy.py

示例6: _function_alias

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def _function_alias(name, version, alias=LIVE):
    try:
        logger.info('creating function alias {0} for {1}:{2}'.format(
            alias, name, version))
        arn = aws_lambda('create_alias',
                         FunctionName=name,
                         FunctionVersion=version,
                         Name=alias,
                         query='AliasArn')
    except ClientError:
        logger.info('alias {0} exists. updating {0} -> {1}:{2}'.format(
            alias, name, version))
        arn = aws_lambda('update_alias',
                         FunctionName=name,
                         FunctionVersion=version,
                         Name=alias,
                         query='AliasArn')
    return arn 
开发者ID:Alephbet,项目名称:gimel,代码行数:20,代码来源:deploy.py

示例7: role

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def role():
    new_role = False
    try:
        logger.info('finding role')
        iam('get_role', RoleName='cronyo')
    except ClientError:
        logger.info('role not found. creating')
        iam('create_role', RoleName='cronyo',
            AssumeRolePolicyDocument=ASSUMED_ROLE_POLICY)
        new_role = True

    role_arn = iam('get_role', RoleName='cronyo', query='Role.Arn')
    logger.debug('role_arn={}'.format(role_arn))

    logger.info('updating role policy')

    iam('put_role_policy', RoleName='cronyo', PolicyName='cronyo',
        PolicyDocument=POLICY)

    if new_role:
        from time import sleep
        logger.info('waiting for role policy propagation')
        sleep(5)

    return role_arn 
开发者ID:cronyo,项目名称:cronyo,代码行数:27,代码来源:deploy.py

示例8: read_metadata_from_s3

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def read_metadata_from_s3(bucket, key):
    try:
        obj = s3_client.get_object(
            Bucket=bucket,
            Key=key
        )
    except ClientError as e:
        error = e.response['Error']['Message']
        logger.info("Exception occurred while reading asset metadata from s3: {e}".format(e=error))
        return {"Status": "Error", "Message": error}
    except Exception as e:
        logger.error("Exception occurred while reading asset metadata from s3")
        return {"Status": "Error", "Message": e}
    else:
        results = obj['Body'].read().decode('utf-8')
        return {"Status": "Success", "Object": results} 
开发者ID:awslabs,项目名称:aws-media-insights-engine,代码行数:18,代码来源:app.py

示例9: delete_s3_objects

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def delete_s3_objects(keys):
    objects = []
    for key in keys:
        objects.append({"Key": key})
    try:
        response = s3_client.delete_objects(
            Bucket=dataplane_s3_bucket,
            Delete={
                'Objects': objects
            }
        )
    except ClientError as e:
        error = e.response['Error']['Message']
        logger.info("Exception occurred while deleting asset metadata from s3: {e}".format(e=error))
        return {"Status": "Error", "Message": error}
    except Exception as e:
        logger.error("Exception occurred while deleting asset metadata from s3")
        return {"Status": "Error", "Message": e}
    else:
        return {"Status": "Success", "Message": response} 
开发者ID:awslabs,项目名称:aws-media-insights-engine,代码行数:22,代码来源:app.py

示例10: s3_verify_bucket_exists

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def s3_verify_bucket_exists(self, bucketname):
        """
        Verifies whether a bucket with the given bucketname exists
        Args:
            bucketname : The bucket name to be verified

        Returns:
              bool: True if bucket exists, False otherwise

        """
        try:
            self.s3_resource.meta.client.head_bucket(Bucket=bucketname)
            logger.info(f"{bucketname} exists")
            return True
        except ClientError:
            logger.info(f"{bucketname} does not exist")
            return False 
开发者ID:red-hat-storage,项目名称:ocs-ci,代码行数:19,代码来源:mcg.py

示例11: discover_resources

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def discover_resources(**kwargs):

    discovered_buckets = []    
    for handler in AWSHandler.objects.all():
        set_progress('Connecting to Amazon S3 for handler: {}'.format(handler))
        conn = boto3.resource(
            's3',
            aws_access_key_id=handler.serviceaccount,
            aws_secret_access_key=handler.servicepasswd,
        )

        try:
            for bucket in conn.buckets.all():
                discovered_buckets.append({
                    "s3_bucket_name": bucket.name,
                    "aws_rh_id": handler.id,
                    "created_in_s3": str(bucket.creation_date)
                })
        except ClientError as e:
            set_progress('AWS ClientError: {}'.format(e))
            continue
            
    return discovered_buckets 
开发者ID:CloudBoltSoftware,项目名称:cloudbolt-forge,代码行数:25,代码来源:discover_s3_buckets.py

示例12: swf_exception_wrapper

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def swf_exception_wrapper():
    try:
        yield
    except ClientError as err:
        err_type = err.response['Error'].get('Code', 'SWFResponseError')
        err_msg = err.response['Error'].get(
            'Message', 'No error message provided...')

        raise _swf_fault_exception.get(err_type, SWFResponseError)(err_msg) 
开发者ID:boto,项目名称:botoflow,代码行数:11,代码来源:swf_exceptions.py

示例13: _bucket_exists

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def _bucket_exists(self):
        """Check if the bucket exists."""
        try:
            self.s3client.get_bucket_location(Bucket=self.bucket)
            return True
        except ClientError as error:
            LOG.error(error)
            return False 
开发者ID:foremast,项目名称:foremast,代码行数:10,代码来源:s3apps.py

示例14: assert_condition_check_fails

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def assert_condition_check_fails():
    try:
        yield
    except (PutError, UpdateError, DeleteError) as e:
        assert isinstance(e.cause, ClientError)
        assert e.cause_response_code == "ConditionalCheckFailedException"
    except TransactWriteError as e:
        assert isinstance(e.cause, ClientError)
        assert e.cause_response_code == "TransactionCanceledException"
        assert "ConditionalCheckFailed" in e.cause_response_message
    else:
        raise AssertionError("The version attribute conditional check should have failed.") 
开发者ID:pynamodb,项目名称:PynamoDB,代码行数:14,代码来源:optimistic_locking.py

示例15: _clear_method

# 需要导入模块: from botocore import client [as 别名]
# 或者: from botocore.client import ClientError [as 别名]
def _clear_method(api_id, resource_id, http_method):
    try:
        method = apigateway('get_method', restApiId=api_id,
                            resourceId=resource_id,
                            httpMethod=http_method)
    except ClientError:
        method = None
    if method:
        apigateway('delete_method', restApiId=api_id, resourceId=resource_id,
                   httpMethod=http_method) 
开发者ID:Alephbet,项目名称:gimel,代码行数:12,代码来源:deploy.py


注:本文中的botocore.client.ClientError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。