How can I easily determine if a Boto 3 S3 bucket resource exists?

后端 未结 6 1572
滥情空心
滥情空心 2020-12-29 01:34

For example, I have this code:

import boto3

s3 = boto3.resource(\'s3\')

bucket = s3.Bucket(\'my-bucket-name\')

# Does it exist???
6条回答
  •  感动是毒
    2020-12-29 01:53

    At the time of this writing there is no high-level way to quickly check whether a bucket exists and you have access to it, but you can make a low-level call to the HeadBucket operation. This is the most inexpensive way to do this check:

    from botocore.client import ClientError
    
    try:
        s3.meta.client.head_bucket(Bucket=bucket.name)
    except ClientError:
        # The bucket does not exist or you have no access.
    

    Alternatively, you can also call create_bucket repeatedly. The operation is idempotent, so it will either create or just return the existing bucket, which is useful if you are checking existence to know whether you should create the bucket:

    bucket = s3.create_bucket(Bucket='my-bucket-name')
    

    As always, be sure to check out the official documentation.

    Note: Before the 0.0.7 release, meta was a Python dictionary.

提交回复
热议问题