當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。