简体   繁体   English

如何检查AWS S3存在桶?

[英]How can I check that a AWS S3 bucket exists?

Simple question here? 简单问题在这里? ... ...

How can I check with boto that a AWS bucket exists? 如何查看boto是否存在AWS存储桶? ... preferably by providing the path? ...最好通过提供路径? ... ...

here is the approach I feel like taking: 这是我想采取的方法:

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

In the code above I am interested to find if a bucket exists amongst the buckets that this AWS Account owns ... 在上面的代码中,我有兴趣发现此AWS账户拥有的存储桶中是否存在存储桶...

IS there a better way to find out if a bucket exists? 有没有更好的方法来确定存在桶? How would I implement a better way? 我该如何实施更好的方法?

Thanks 谢谢

From the documentation: 从文档:

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. 如果您不确定存在桶是否存在,则可以使用S3Connection.lookup方法,该方法将返回有效存储桶或None。

So this is the best option: 所以这是最好的选择:

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

You could just try and load the bucket (as you are doing now). 您可以尝试加载存储桶(正如您现在所做的那样)。 By default the method is set to validate if the bucket exists. 默认情况下,该方法设置为验证存储桶是否存在。

You could also just try to "lookup" the bucket. 您也可以尝试“查找”存储桶。 The method will raise an S3ResponseError. 该方法将引发S3ResponseError。

Ether way, you'll have to make an API call so I think you're left to personal preference here (whether you like dealing with exceptions, or simply checking for None). 以太方式,你必须进行API调用,所以我认为你在这里留下个人偏好(无论你喜欢处理异常,还是只是检查无)。

So you have a couple of options here: 所以你有几个选择:

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

Or: 要么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM