如何使用 Boto3 和 AWS Resource 确定 S3 中是否存在根存储桶?
问题陈述-使用Python中的Boto3库来确定S3中是否存在根存储桶。
示例-Bucket_1在S3中是否存在。
解决这个问题的方法/算法
步骤1-导入boto3和botocore异常以处理异常。
步骤2-使用boto3库创建AWS会话。
步骤3-为S3创建AWS资源。
第4步-使用功能head_bucket()。如果存储桶存在且用户有权访问它,则返回200OK 。否则,响应将是403Forbidden或404NotFound。
步骤5-根据响应代码处理异常。
Step6-根据桶是否存在返回真/假。
示例
以下代码检查S3中是否存在根存储桶-
import boto3
frombotocore.exceptionsimport ClientError
# To check whether root bucket exists or not
def bucket_exists(bucket_name):
try:
session = boto3.session.Session()
# User can pass customized access key, secret_key and token as well
s3_resource = session.resource('s3')
s3_resource.meta.client.head_bucket(Bucket=bucket_name)
print("存储桶存在。", bucket_name)
exists = True
except ClientError as error:
error_code = int(error.response['Error']['Code'])
if error_code == 403:
print("Private Bucket. Forbidden Access! ", bucket_name)
elif error_code == 404:
print("桶不存在!", bucket_name)
exists = False
return exists
print(bucket_exists('bucket_1'))
print(bucket_exists('AWS_bucket_1'))输出结果存储桶存在。 bucket_1 True 桶不存在! AWS_bucket_1 False