Python 如何使用Boto3和AWS客户端确定S3中是否存在根存储桶?
问题陈述 - 使用Python中的Boto3库确定S3中是否存在根存储桶。
示例 - 检查Bucket_1在S3中是否存在。
阅读更多:Python 教程
解决此问题的方法/算法
第1步 - 导入boto3和botocore异常以处理异常。
第2步 - 使用boto3库创建AWS会话。
第3步 - 为S3创建AWS客户端。
第4步 - 使用函数 head_bucket() 。 如果存储桶存在且用户有访问权限,它将返回 200 OK 。否则,响应将是 403 Forbidden 或 404 Not Found 。
第5步 - 根据响应代码处理异常。
第6步 - 根据存储桶是否存在返回True / False。
示例
以下代码检查根存储桶是否存在于S3中 –
import boto3
from botocore.exceptions import ClientError
#检查根存储桶是否存在
def bucket_exists(bucket_name):
try:
session = boto3.session.Session()
#用户还可以自定义访问密钥,secret_key和token
s3_client = session.client('s3')
s3_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("私有存储桶. 禁止访问!", 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
极客教程