如何使用 Boto3 和 AWS 资源来确定 S3 中是否存在根存储桶?
问题陈述 − 使用 Python 中的 Boto3 库来确定 S3 中是否存在根存储桶。
示例 − 存储桶 Bucket_1 是否存在于 S3 中。
解决此问题的方法/算法
步骤 1 − 导入 boto3 和 botocore 异常以处理异常。
步骤 2 − 使用 boto3 库创建 AWS 会话。
步骤 3 − 为 S3 创建 AWS 资源。
步骤 4 − 使用函数 head_bucket()。如果存储桶存在并且用户有权访问它,则返回 200 OK。否则,响应将为 403 禁止或 404 未找到。
步骤 5 − 根据响应代码处理异常。
步骤 6 − 根据存储桶是否存在返回 True/False。
示例
以下代码检查 S3 中是否存在根存储桶 −
import boto3
from botocore.exceptions import 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 exists.", 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 Does Not Exist!", bucket_name)
exists = False
return exists
print(bucket_exists('bucket_1'))
print(bucket_exists('AWS_bucket_1'))输出
Bucket exists. bucket_1 True Bucket Does Not Exist! AWS_bucket_1 False
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP