Python 如何使用Boto3和AWS资源确定S3中是否存在根bucket?

Python 如何使用Boto3和AWS资源确定S3中是否存在根bucket?

问题陈述 - 使用Python中的Boto3库确定S3中是否存在根bucket。

例子 - Bucket_1是否存在于S3中。

阅读更多:Python 教程

解决这个问题的方法/算法

第一步 - 导入Boto3和botocore exceptions处理异常。

第二步 - 使用Boto3库创建AWS会话。

第三步 - 为S3创建AWS资源。

第四步 - 使用函数 head_bucket() 。 它返回 200 OK ,如果bucket存在且用户有访问权限。 否则,响应将是 403 Forbidden404 Not Found

第五步 - 根据响应代码处理异常。

第六步 - 根据bucket是否存在返回True/False。

例子

以下代码检查S3中是否存在根bucket-

import boto3
from botocore.exceptions import ClientError

# 检查根bucket是否存在
def bucket_exists(bucket_name):
   try:
      session = boto3.session.Session()
      # 用户也可以自定义访问密钥、密钥和令牌
      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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程