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

后端 未结 6 1582
滥情空心
滥情空心 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:50

    you can use conn.get_bucket

    from boto.s3.connection import S3Connection
    from boto.exception import S3ResponseError    
    
    conn = S3Connection(aws_access_key, aws_secret_key)
    
    try:
        bucket = conn.get_bucket(unique_bucket_name, validate=True)
    except S3ResponseError:
        bucket = conn.create_bucket(unique_bucket_name)
    

    quoting the documentation at http://boto.readthedocs.org/en/latest/s3_tut.html

    As of Boto v2.25.0, this now performs a HEAD request (less expensive but worse error messages).

提交回复
热议问题