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


Python exceptions.NoCredentialsError方法代码示例

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


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

示例1: get_filepath_or_buffer

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def get_filepath_or_buffer(filepath_or_buffer, encoding=None,
                           compression=None, mode=None):

    if mode is None:
        mode = 'rb'

    fs = s3fs.S3FileSystem(anon=False)
    try:
        filepath_or_buffer = fs.open(_strip_schema(filepath_or_buffer), mode)
    except (compat.FileNotFoundError, NoCredentialsError):
        # boto3 has troubles when trying to access a public file
        # when credentialed...
        # An OSError is raised if you have credentials, but they
        # aren't valid for that bucket.
        # A NoCredentialsError is raised if you don't have creds
        # for that bucket.
        fs = s3fs.S3FileSystem(anon=True)
        filepath_or_buffer = fs.open(_strip_schema(filepath_or_buffer), mode)
    return filepath_or_buffer, None, compression, True 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:s3.py

示例2: _do_download

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def _do_download(request, s3_client):
        """ Does the download from s3
        """
        _, _, bucket_name, url_key = request.url.split('/', 3)

        try:
            response = s3_client.get_object(Bucket=bucket_name, Key=url_key, RequestPayer='requester')
            return response['Body'].read()
        except NoCredentialsError:
            raise ValueError(
                'The requested data is in Requester Pays AWS bucket. In order to download the data please set '
                'your access key either in AWS credentials file or in sentinelhub config.json file using '
                'command line:\n'
                '$ sentinelhub.config --aws_access_key_id <your AWS key> --aws_secret_access_key '
                '<your AWS secret key>')
        except s3_client.exceptions.NoSuchKey:
            raise AwsDownloadFailedException('File in location %s is missing' % request.url)
        except s3_client.exceptions.NoSuchBucket:
            raise ValueError('Aws bucket %s does not exist' % bucket_name) 
开发者ID:sentinel-hub,项目名称:sentinelhub-py,代码行数:21,代码来源:aws_client.py

示例3: validate_configuration

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def validate_configuration(self, config):
        """See :meth:`storage.brokers.broker.Broker.validate_configuration`"""

        warnings = []
        if 'bucket_name' not in config or not config['bucket_name']:
            raise InvalidBrokerConfiguration('INVALID_BROKER', 'S3 broker requires "bucket_name" to be populated')
        region_name = config.get('region_name')

        credentials = AWSClient.instantiate_credentials_from_config(config)

        # Check whether the bucket can actually be accessed
        with S3Client(credentials, region_name) as client:
            try:
                client.get_bucket(config['bucket_name'])
            except (ClientError, NoCredentialsError):
                warnings.append(ValidationWarning('bucket_access',
                                                  'Unable to access bucket. Check the bucket name and credentials.'))

        return warnings 
开发者ID:ngageoint,项目名称:scale,代码行数:21,代码来源:s3_broker.py

示例4: _get_account_info

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def _get_account_info(self, profile):
        partition, region = self._get_partition(profile)
        session = self.session(profile, region)
        sts_client = session.client("sts", region_name=region)
        try:
            account_id = sts_client.get_caller_identity()["Account"]
        except ClientError as e:
            if e.response["Error"]["Code"] == "AccessDenied":
                raise TaskCatException(
                    f"Not able to fetch account number from {region} using profile "
                    f"{profile}. {str(e)}"
                )
            raise
        except NoCredentialsError as e:
            raise TaskCatException(
                f"Not able to fetch account number from {region} using profile "
                f"{profile}. {str(e)}"
            )
        except ProfileNotFound as e:
            raise TaskCatException(
                f"Not able to fetch account number from {region} using profile "
                f"{profile}. {str(e)}"
            )
        return {"partition": partition, "account_id": account_id} 
开发者ID:aws-quickstart,项目名称:taskcat,代码行数:26,代码来源:_client_factory.py

示例5: main

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def main():
    option_list = 'region= type= role= key= volume= ami= bootstrap='.split()
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], '', option_list)
    except:
        usage()
        sys.exit(2)
    if len(args) > 0:
        if args[0] == 'configure':
            configure()
        elif args[0] in os_list:
            try:
                launch(opts, args[0])
            except NoCredentialsError:
                advise_credentials()
            except:
                troubleshoot()
        elif args[0] == 'help':
            usage()
        else:
            usage()
    else:
        usage() 
开发者ID:awslabs,项目名称:aws-support-tools,代码行数:25,代码来源:qi.py

示例6: to_string

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def to_string(self):
    template_config = {
      "project_name": config.project_name
    }

    try:
      template_config["project_repo"] = self.ecr.project_repo
    except NoCredentialsError:
      print_yellow("WARNING: Could not get template variable project_repo")

    if config.template_config_files:
      for template_config_file in config.template_config_files:
        try:
          config_loader = ConfigLoader(template_config_file)
          template_config.update(config_loader.load())
        except NoCredentialsError:
          print_yellow("WARNING: Could not get template config file %s" % template_config_file)

    return TemplateRenderer(self.template_file, template_config).render() 
开发者ID:artsy,项目名称:hokusai,代码行数:21,代码来源:yaml_spec.py

示例7: file_exists

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def file_exists(cls, file_path):
        if isinstance(file_path, str):
            match = S3_ADDRESS_REGEX.search(file_path)
            if match is not None:
                if file_path[0] == "S":
                    file_path = "{}{}".format("s", file_path[1:])
                import s3fs as S3FS
                from botocore.exceptions import NoCredentialsError

                s3fs = S3FS.S3FileSystem(anon=False)
                exists = False
                try:
                    exists = s3fs.exists(file_path) or exists
                except NoCredentialsError:
                    pass
                s3fs = S3FS.S3FileSystem(anon=True)
                return exists or s3fs.exists(file_path)
        return os.path.exists(file_path) 
开发者ID:modin-project,项目名称:modin,代码行数:20,代码来源:file_reader.py

示例8: invalidate_cloudfront_caches

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def invalidate_cloudfront_caches():
    try:
        distribution = CloudfrontDistribution.objects.all()[0]
        client = boto3.client('cloudfront')
        response = client.create_invalidation(
            DistributionId=distribution.distribution_id,
            InvalidationBatch={
                'Paths': {
                    'Quantity': 1,
                    'Items': [
                        '/apps/cms/api/*' # invalidate the entire cache for the website
                    ],
                },
                'CallerReference': str(datetime.datetime.now().strftime('%m%d%Y%H%M'))
            }
        )
    except CloudfrontDistribution.DoesNotExist:
        return
    except IndexError:
        return
    except NoCredentialsError:
        print('No AWS credentials set - unable to invalidate cache')
    except ClientError as e:
            print("Unexpected AWS error: %s" % e) 
开发者ID:openstax,项目名称:openstax-cms,代码行数:26,代码来源:functions.py

示例9: get

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def get(self, paths=['/'], flat=True):
        p = self.ssm.get_paginator('get_parameters_by_path')
        output = {}
        for path in paths:
            try:
                for page in p.paginate(
                    Path=path,
                    Recursive=True,
                    WithDecryption=True):
                    for param in page['Parameters']:
                        add(obj=output,
                            path=param['Name'],
                            value=self._read_param(param['Value'], param['Type']))
            except (ClientError, NoCredentialsError) as e:
                print("Failed to fetch parameters from SSM!", e, file=sys.stderr)

        return flatten(output) if flat else output 
开发者ID:runtheops,项目名称:ssm-diff,代码行数:19,代码来源:states.py

示例10: _get_sts_access

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [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"),
    ) 
开发者ID:project-koku,项目名称:koku,代码行数:29,代码来源:provider.py

示例11: check_credentials

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def check_credentials(self):
        """Verifies key/secret/host combination by making a balance inquiry"""
        try:
            return bool(self.mturk.get_account_balance())
        except NoCredentialsError:
            raise MTurkServiceException("No AWS credentials set!")
        except ClientError:
            raise MTurkServiceException("Invalid AWS credentials!")
        except Exception as ex:
            raise MTurkServiceException(
                "Error checking credentials: {}".format(str(ex))
            ) 
开发者ID:Dallinger,项目名称:Dallinger,代码行数:14,代码来源:mturk.py

示例12: check_credentials

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def check_credentials():
    """Check for valid AWS credentials in environment variables

    Returns:
        bool: True any of the AWS env variables exist
    """
    try:
        response = boto3.client('sts').get_caller_identity()
    except NoCredentialsError:
        LOGGER.error('No valid AWS Credentials found in your environment!')
        LOGGER.error('Please follow the setup instructions here: '
                     'https://www.streamalert.io/getting-started.html'
                     '#configure-aws-credentials')
        return False
    except ClientError as err:
        # Check for an error related to an expired token
        if err.response['Error']['Code'] == 'ExpiredToken':
            LOGGER.error('%s. Please refresh your credentials.', err.response['Error']['Message'])
            return False
        raise  # Raise the error if it is anything else

    LOGGER.debug(
        'Using credentials for user \'%s\' with user ID \'%s\' in account '
        '\'%s\'', response['Arn'], response['UserId'], response['Account']
    )

    return True 
开发者ID:airbnb,项目名称:streamalert,代码行数:29,代码来源:helpers.py

示例13: test_check_for_bucket_raises_error_with_invalid_conn_id

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def test_check_for_bucket_raises_error_with_invalid_conn_id(self, s3_bucket, monkeypatch):
        monkeypatch.delenv('AWS_PROFILE', raising=False)
        monkeypatch.delenv('AWS_ACCESS_KEY_ID', raising=False)
        monkeypatch.delenv('AWS_SECRET_ACCESS_KEY', raising=False)
        hook = S3Hook(aws_conn_id="does_not_exist")
        with pytest.raises(NoCredentialsError):
            hook.check_for_bucket(s3_bucket) 
开发者ID:apache,项目名称:airflow,代码行数:9,代码来源:test_s3.py

示例14: test_check_for_key_raises_error_with_invalid_conn_id

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def test_check_for_key_raises_error_with_invalid_conn_id(self, monkeypatch, s3_bucket):
        monkeypatch.delenv('AWS_PROFILE', raising=False)
        monkeypatch.delenv('AWS_ACCESS_KEY_ID', raising=False)
        monkeypatch.delenv('AWS_SECRET_ACCESS_KEY', raising=False)
        hook = S3Hook(aws_conn_id="does_not_exist")
        with pytest.raises(NoCredentialsError):
            hook.check_for_key('a', s3_bucket) 
开发者ID:apache,项目名称:airflow,代码行数:9,代码来源:test_s3.py

示例15: checkAwsCreds

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import NoCredentialsError [as 别名]
def checkAwsCreds():
    """
    Checks to see if the user has credentials for AWS properly configured.
    This is essentially a requirement for getting accurate results.

    :return: True if AWS credentials are properly configured. False if not.
    """

    sts = boto3.client('sts')
    try:
        response = sts.get_caller_identity()
    except NoCredentialsError as e:
            return False

    return True 
开发者ID:sa7mon,项目名称:S3Scanner,代码行数:17,代码来源:s3utils.py


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