如何使用 Wait 功能检查 S3 bucket 中的 key 是否存在,使用 Boto3 和 AWS Client?

boto3pythonserver side programmingprogramming更新于 2024/1/10 23:48:00

当用户想要使用 wait 功能在编程代码中验证 bucket 中的 key 是否存在时。

问题陈述 − 使用 Python 中的 boto3 库检查 bucket 中是否存在 key,使用 waiters 功能。例如,使用 waiters 检查 Bucket_1 中是否存在 key test.zip。

解决此问题的方法/算法

步骤 1 − 导入 boto3 和 botocore 异常来处理异常。

步骤 2 − bucket_name 和 key 是函数中的两个参数。

步骤 3 −使用 boto3 库创建 AWS 会话。

步骤 4 − 为 S3 创建 AWS 客户端。

步骤 5 − 现在使用 get_waiter 函数为 object_exists 创建等待对象

步骤 6 − 现在,使用 wait  对象验证给定存储桶中是否存在密钥。默认情况下,它每 5 秒检查一次,直到达到成功状态。20 次检查失败后将返回错误。但是,用户可以定义轮询时间和最大尝试次数。

步骤 7 − 它返回 None。

步骤 8 −如果检查存储桶时出现错误,则处理通用异常。

示例

使用以下代码使用 waiter  检查存储桶中是否存在某个键 −

import boto3
from botocore.exceptions import ClientError

def use_waiters_check_object_exists(bucket_name, key_name):
   session = boto3.session.Session()
   s3_client = session.client('s3')
   try:
      waiter = s3_client.get_waiter('object_exists')
      waiter.wait(Bucket=bucket_name, Key = key_name,
                  WaiterConfig={
                     'Delay': 2, 'MaxAttempts': 5})
      print('Object exists: ' + bucket_name +'/'+key_name)
   except ClientError as e:
      raise Exception( "boto3 client error in use_waiters_check_object_exists: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in use_waiters_check_object_exists: " + e.__str__())

print(use_waiters_check_object_exists("Bucket_1","testfolder/test.zip"))
print(use_waiters_check_object_exists("Bucket_1","testfolder/test1.zip")
)

输出

Object exists: Bucket_1/testfolder/test.zip
None

botocore.exceptions.WaiterError: Waiter ObjectExists failed: Max
attempts exceeded
"Unexpected error in use_waiters_check_object_exists: " + e.__str__())
Exception: Unexpected error in use_waiters_check_object_exists: Waiter
ObjectExists failed: Max attempts exceed

对于 Bucket_1/testfolder/test.zip,输出为打印语句和 None。由于响应未返回任何内容,因此会打印 None。

对于 Bucket_1/testfolder/test1.zip,输出为异常,因为此对象不存在。

在异常中,可以读取到已超出最大尝试次数。


相关文章