如何使用 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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下