For example, I have this code:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')
# Does it exist???
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.