【问题标题】:Print message instead of error S3 policy BOTO3打印消息而不是错误 S3 策略 BOTO3
【发布时间】:2021-04-12 15:27:08
【问题描述】:

我应该为那些存在的存储桶获取策略,并且只是为不存在 olicy 的存储桶获取正常的错误语句。使用以下代码获取 s3 存储桶策略:

s3=boto3.client("s3",aws_access_key_id=access_key_id,aws_secret_access_key=secret_key)
for i in Bucket_Name:                              #Bucket_name stores the name of the buckets
     policy = s3.get_bucket_policy(Bucket=i)
     print(policy['Policy'])

现在,对于有策略的存储桶,它会打印出下摆,但对于没有策略的存储桶,它会发出以下错误,并停止进一步执行。 botocore.exceptions.ClientError: 调用 GetBucketPolicy 操作时发生错误 (NoSuchBucketPolicy):存储桶策略不存在

有没有办法打印一些消息而不是这个错误并继续为所有其他存储桶执行代码?

【问题讨论】:

  • 添加了一个解决方案,以及来自官方 boto 页面的文档 :)

标签: amazon-web-services amazon-s3 boto3


【解决方案1】:

Botocore 异常是在 botocore 包中静态定义的。您创建的任何 Boto3 客户端都将使用这些相同的静态定义异常类。 The most common botocore exception you’ll encounter is ClientError.(这也是你的代码中的相同错误) 当 AWS 服务为您的 Boto3 客户端的请求提供错误响应时,这是一个一般例外。 docs for reference

这样试试

import botocore
import boto3

client = boto3.client('aws_service_name')

try:
    client.some_api_call(SomeParam='some_param')
    #your code here
    for i in Bucket_Name:
      policy = s3.get_bucket_policy(Bucket=i)
      print(policy['Policy'])

except botocore.exceptions.ClientError as error:
    # Put your error handling logic here
    

except botocore.exceptions.ParamValidationError as error:
    raise ValueError('The parameters you provided are incorrect: {}'.format(error)) #for parameter validation kind of error

【讨论】:

    【解决方案2】:

    这段代码将处理异常:

    s3 = boto3.client("s3", aws_access_key_id=access_key_id, aws_secret_access_key=secret_key)
    for i in Bucket_Name:
        try:  # Bucket_name stores the name of the buckets
            policy = s3.get_bucket_policy(Bucket=i)
            print(policy['Policy'])
        except ClientError:
            print(f'The bucket {i} does not have a policy')
    

    【讨论】:

    • 抛出以下错误:NameError: name 'ClientError' is not defined
    • 从 botocore.exceptions 导入 ClientError
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2016-12-03
    • 2021-03-29
    • 2016-05-30
    相关资源
    最近更新 更多