如何检查 AWS S3 存储桶是否存在?

How can I check that a AWS S3 bucket exists?

简单的问题? ...

如何使用 boto 检查 AWS 存储桶是否存在? ...最好通过提供路径? ...

这是我想采用的方法:

def bucket_exists(self, bucket_name):
    connection = boto.s3.connection.S3Connection('<aws access key>', '<aws secret key>')
    buckets = connection.get_all_buckets()
    for bucket in buckets:
        bucket_name = bucket.name
        # Bucket existence logic here
        # submit boto request
        ie:. exists = boto.get_bucket(bucket_name, validate=True)
        if exists:
            return True
        else:
            return False

在上面的代码中,我有兴趣查找此 AWS 帐户拥有的存储桶中是否存在存储桶...

是否有更好的方法来确定存储桶是否存在?我将如何实施更好的方法?

谢谢

您可以尝试加载桶(就像您现在所做的那样)。默认情况下,该方法设置为验证存储桶是否存在。

您也可以尝试 "lookup" 存储桶。该方法将引发 S3ResponseError。

Ether 方法,您必须进行 API 调用,所以我认为您在这里可以根据个人喜好选择(无论您是喜欢处理异常,还是只是检查 None) .

所以你在这里有几个选择:

bucket = connection.lookup('this-is-my-bucket-name')
if bucket is None:
    print "This bucket doesn't exist."

或者:

try:
    bucket = connection.get_bucket('this-is-my-bucket-name')
except S3ResponseError:
    print "This bucket doesn't exist."

来自文档:

If you are unsure if the bucket exists or not, you can use the S3Connection.lookup method, which will either return a valid bucket or None.

所以这是最好的选择:

bucket = connection.lookup('this-is-my-bucket-name')
if not bucket:
    print "This bucket doesn't exist."