當前位置: 首頁>>代碼示例>>Python>>正文


Python boto3.exceptions方法代碼示例

本文整理匯總了Python中boto3.exceptions方法的典型用法代碼示例。如果您正苦於以下問題:Python boto3.exceptions方法的具體用法?Python boto3.exceptions怎麽用?Python boto3.exceptions使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在boto3的用法示例。


在下文中一共展示了boto3.exceptions方法的7個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _native_download_file

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def _native_download_file(meta, full_dst_file_name, max_concurrency):
        logger = getLogger(__name__)
        try:
            akey = SnowflakeS3Util._get_s3_object(meta, meta['src_file_name'])
            akey.download_file(
                full_dst_file_name,
                Callback=meta['get_callback'](
                    meta['src_file_name'],
                    meta['src_file_size'],
                    output_stream=meta['get_callback_output_stream'],
                    show_progress_bar=meta['show_progress_bar']) if
                meta['get_callback'] else None,
                Config=TransferConfig(
                    multipart_threshold=SnowflakeS3Util.DATA_SIZE_THRESHOLD,
                    max_concurrency=max_concurrency,
                    num_download_attempts=10,
                )
            )
            meta['result_status'] = ResultStatus.DOWNLOADED
        except botocore.exceptions.ClientError as err:
            if err.response['Error']['Code'] == EXPIRED_TOKEN:
                meta['result_status'] = ResultStatus.RENEW_TOKEN
            else:
                logger.debug(
                    "Failed to download a file: %s, err: %s",
                    full_dst_file_name, err, exc_info=True)
                raise err
        except RetriesExceededError as err:
            meta['result_status'] = ResultStatus.NEED_RETRY
            meta['last_error'] = err
        except OpenSSL.SSL.SysCallError as err:
            meta['last_error'] = err
            if err.args[0] == ERRORNO_WSAECONNABORTED:
                # connection was disconnected by S3
                # because of too many connections. retry with
                # less concurrency to mitigate it

                meta[
                    'result_status'] = ResultStatus.NEED_RETRY_WITH_LOWER_CONCURRENCY
            else:
                meta['result_status'] = ResultStatus.NEED_RETRY 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:43,代碼來源:s3_util.py

示例2: update_dns_zone_record

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def update_dns_zone_record(env, zone_id, **kwargs):
    """Create a Route53 CNAME record in _env_ zone.

    Args:
        env (str): Deployment environment.
        zone_id (str): Route53 zone id.

    Keyword Args:
        dns_name (str): FQDN of application's dns entry to add/update.
        dns_name_aws (str): FQDN of AWS resource
        dns_ttl (int): DNS time-to-live (ttl)
    """
    client = boto3.Session(profile_name=env).client('route53')
    response = {}

    hosted_zone_info = client.get_hosted_zone(Id=zone_id)
    zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')
    dns_name = kwargs.get('dns_name')

    if dns_name and dns_name.endswith(zone_name):
        dns_name_aws = kwargs.get('dns_name_aws')
        # This is what will be added to DNS
        dns_json = get_template(template_file='infrastructure/dns_upsert.json.j2', **kwargs)
        LOG.info('Attempting to create DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,
                 zone_name)
        try:
            response = client.change_resource_record_sets(
                HostedZoneId=zone_id,
                ChangeBatch=json.loads(dns_json), )
            LOG.info('Upserted DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id, zone_name)
        except botocore.exceptions.ClientError as error:
            LOG.info('Error creating DNS record %s (%s) in Hosted Zone %s (%s)', dns_name, dns_name_aws, zone_id,
                     zone_name)
            LOG.debug(error)
    else:
        LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)

    LOG.debug('Route53 JSON Response: \n%s', pformat(response)) 
開發者ID:foremast,項目名稱:foremast,代碼行數:40,代碼來源:dns.py

示例3: add_tags

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def add_tags(self):
        """Add tags to security group.

        Returns:
            True: Upon successful completion.
        """
        session = boto3.session.Session(profile_name=self.env, region_name=self.region)
        resource = session.resource('ec2')
        group_id = get_security_group_id(self.app_name, self.env, self.region)
        security_group = resource.SecurityGroup(group_id)

        try:
            tag = security_group.create_tags(
                DryRun=False,
                Tags=[{
                    'Key': 'app_group',
                    'Value': self.group
                }, {
                    'Key': 'app_name',
                    'Value': self.app_name
                }])
            self.log.debug('Security group has been tagged: %s', tag)
        except botocore.exceptions.ClientError as error:
            self.log.warning(error)

        return True 
開發者ID:foremast,項目名稱:foremast,代碼行數:28,代碼來源:create_securitygroup.py

示例4: track_provisioned

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def track_provisioned(func):
    # type: (Callable[..., T]) -> Callable[..., T]
    """Tracks provisioned exceptions and increments a metric for them named
    after the function decorated"""
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        if TRACK_DB_CALLS:
            DB_CALLS.append(func.__name__)
        return func(self, *args, **kwargs)
    return wrapper 
開發者ID:mozilla-services,項目名稱:autopush,代碼行數:12,代碼來源:db.py

示例5: get_file_header

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def get_file_header(meta, filename):
        """Gets the remote file's metadata.

        Args:
            meta: Remote file's metadata info.
            filename: Name of remote file.

        Returns:
            The file header, with expected properties populated or None, based on how the request goes with the
            storage provider.
        """
        logger = getLogger(__name__)
        akey = SnowflakeS3Util._get_s3_object(meta, filename)
        try:
            # HTTP HEAD request
            akey.load()
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == EXPIRED_TOKEN:
                logger.debug("AWS Token expired. Renew and retry")
                meta['result_status'] = ResultStatus.RENEW_TOKEN
                return None
            elif e.response['Error']['Code'] == '404':
                logger.debug('not found. bucket: %s, path: %s',
                             akey.bucket_name, akey.key)
                meta['result_status'] = ResultStatus.NOT_FOUND_FILE
                return FileHeader(
                    digest=None,
                    content_length=None,
                    encryption_metadata=None,
                )
            elif e.response['Error']['Code'] == '400':
                logger.debug('Bad request, token needs to be renewed: %s. '
                             'bucket: %s, path: %s',
                             e.response['Error']['Message'],
                             akey.bucket_name, akey.key)
                meta['result_status'] = ResultStatus.RENEW_TOKEN
                return None
            logger.debug(
                "Failed to get metadata for %s, %s: %s",
                akey.bucket_name, akey.key, e)
            meta['result_status'] = ResultStatus.ERROR
            return None

        meta['result_status'] = ResultStatus.UPLOADED
        encryption_metadata = EncryptionMetadata(
            key=akey.metadata.get(AMZ_KEY),
            iv=akey.metadata.get(AMZ_IV),
            matdesc=akey.metadata.get(AMZ_MATDESC),
        ) if akey.metadata.get(AMZ_KEY) else None

        return FileHeader(
            digest=akey.metadata.get(SFC_DIGEST),
            content_length=akey.content_length,
            encryption_metadata=encryption_metadata
        ) 
開發者ID:snowflakedb,項目名稱:snowflake-connector-python,代碼行數:57,代碼來源:s3_util.py

示例6: update_failover_dns_record

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def update_failover_dns_record(env, zone_id, **kwargs):
    """Create a Failover Route53 alias record in _env_ zone.

    Args:
        env (str): Deployment environment.
        zone_id (str): Route53 zone id.

    Keyword Args:
        dns_name (str): FQDN of application's dns entry to add/update.
        dns_ttl (int): DNS time-to-live (ttl)
        elb_aws_dns (str): DNS A Record of ELB from AWS
        elb_dns_zone_id (str): Zone ID of ELB DNS
        failover_state (str): if the record is primary or secondary
        primary_region (str): Primary AWS region for DNS
    """
    client = boto3.Session(profile_name=env).client('route53')
    response = {}

    hosted_zone_info = client.get_hosted_zone(Id=zone_id)
    zone_name = hosted_zone_info['HostedZone']['Name'].rstrip('.')
    dns_name = kwargs.get('dns_name')

    # Check that the primary record exists
    failover_state = kwargs.get('failover_state')
    if failover_state.lower() != 'primary':
        primary_record = find_existing_record(env, zone_id, dns_name, check_key='Failover', check_value='PRIMARY')
        if not primary_record:
            raise PrimaryDNSRecordNotFound("Primary Failover DNS record not found: {}".format(dns_name))

    if dns_name and dns_name.endswith(zone_name):
        dns_json = get_template(template_file='infrastructure/dns_failover_upsert.json.j2', **kwargs)
        LOG.info('Attempting to create DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name,
                 kwargs['elb_aws_dns'], zone_id, zone_name)
        try:
            delete_existing_cname(env, zone_id, dns_name)
            response = client.change_resource_record_sets(
                HostedZoneId=zone_id,
                ChangeBatch=json.loads(dns_json), )
            LOG.info('Upserted DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name, kwargs['elb_aws_dns'],
                     zone_id, zone_name)
        except botocore.exceptions.ClientError as error:
            LOG.info('Error creating DNS Failover record %s (%s) in Hosted Zone %s (%s)', dns_name,
                     kwargs['elb_aws_dns'], zone_id, zone_name)
            LOG.debug(error)
    else:
        LOG.info('Skipping creating DNS record %s in non-matching Hosted Zone %s (%s)', dns_name, zone_id, zone_name)

    LOG.debug('Route53 JSON Response: \n%s', pformat(response)) 
開發者ID:foremast,項目名稱:foremast,代碼行數:50,代碼來源:dns.py

示例7: add_cidr_rules

# 需要導入模塊: import boto3 [as 別名]
# 或者: from boto3 import exceptions [as 別名]
def add_cidr_rules(self, rules):
        """Add cidr rules to security group via boto.

        Args:
            rules (list): Allowed Security Group ports and protocols.

        Returns:
            True: Upon successful completion.

        Raises:
            SpinnakerSecurityGroupError: boto3 call failed to add CIDR block to
                Security Group.
        """
        session = boto3.session.Session(profile_name=self.env, region_name=self.region)
        client = session.client('ec2')

        group_id = get_security_group_id(self.app_name, self.env, self.region)

        for rule in rules:
            data = {
                'DryRun':
                False,
                'GroupId':
                group_id,
                'IpPermissions': [{
                    'IpProtocol': rule['protocol'],
                    'FromPort': rule['start_port'],
                    'ToPort': rule['end_port'],
                    'IpRanges': [{
                        'CidrIp': rule['app']
                    }]
                }]
            }
            self.log.debug('Security Group rule: %s', data)

            try:
                client.authorize_security_group_ingress(**data)
            except botocore.exceptions.ClientError as error:
                if 'InvalidPermission.Duplicate' in str(error):
                    self.log.debug('Duplicate rule exist, that is OK.')
                else:
                    msg = 'Unable to add cidr rules to {}'.format(rule.get('app'))
                    self.log.error(msg)
                    raise SpinnakerSecurityGroupError(msg)

        return True 
開發者ID:foremast,項目名稱:foremast,代碼行數:48,代碼來源:create_securitygroup.py


注:本文中的boto3.exceptions方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。