使用boto3检查s3中的存储桶中是否存在密钥

2024-04-20 16:03:12 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

Boto 2的boto.s3.key.Key对象曾经有一个exists方法,该方法通过执行HEAD请求并查看结果来检查S3上是否存在密钥,但似乎已经不存在了。你必须自己做:

import boto3
import botocore

s3 = boto3.resource('s3')

try:
    s3.Object('my-bucket', 'dootdoot.jpg').load()
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        # The object does not exist.
        ...
    else:
        # Something else has gone wrong.
        raise
else:
    # The object does exist.
    ...

load()对单个键执行HEAD请求,这很快,即使所讨论的对象很大,或者您的bucket中有许多对象。

当然,您可能正在检查对象是否存在,因为您正计划使用它。如果是这种情况,您可以忘记load(),直接执行get()download_file(),然后在那里处理错误情况。

我不太喜欢使用异常来控制流。这是一种适用于boto3的替代方法:

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
key = 'dootdoot.jpg'
objs = list(bucket.objects.filter(Prefix=key))
if len(objs) > 0 and objs[0].key == key:
    print("Exists!")
else:
    print("Doesn't exist")

我发现最简单的方法(可能也是最有效的方法)是:

import boto3
from botocore.errorfactory import ClientError

s3 = boto3.client('s3')
try:
    s3.head_object(Bucket='bucket_name', Key='file_path')
except ClientError:
    # Not found
    pass

相关问题 更多 >