How can I check that a AWS S3 bucket exists?

别等时光非礼了梦想. 提交于 2019-12-05 12:14:34

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.

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).

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."
lmo

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.

So this is the best option:

bucket = connection.lookup('this-is-my-bucket-name')
if not bucket:
    print "This bucket doesn't exist."
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!