例如,我有这个代码:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')
# Does it exist???
例如,我有这个代码:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')
# Does it exist???
在撰写本文时,还没有高级方法可以快速检查存储桶是否存在以及您是否可以访问它,但您可以对 HeadBucket 操作进行低级调用。这是进行此检查的最便宜的方法:
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.
或者,您也可以create_bucket
反复调用。该操作是幂等的,因此它将创建或仅返回现有存储桶,这在您检查存在以了解是否应该创建存储桶时很有用:
bucket = s3.create_bucket(Bucket='my-bucket-name')
与往常一样,请务必查看官方文档。
注意:在 0.0.7 版本之前,meta
是一个 Python 字典。
正如@Daniel 所述,Boto3 文档建议的最佳方法是使用head_bucket()
head_bucket() - 此操作对于确定存储桶是否存在以及您是否有权访问它很有用。
如果您的存储桶数量较少,则可以使用以下内容:
>>> import boto3
>>> s3 = boto3.resource('s3')
>>> s3.Bucket('Hello') in s3.buckets.all()
False
>>> s3.Bucket('some-docs') in s3.buckets.all()
True
>>>
我在这方面取得了成功:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')
if bucket.creation_date:
print("The bucket exists")
else:
print("The bucket does not exist")
我试过丹尼尔的例子,它真的很有帮助。跟进 boto3 文档,这是我干净的测试代码。当存储桶是私有的并返回“禁止!”时,我添加了对“403”错误的检查。错误。
import boto3, botocore
s3 = boto3.resource('s3')
bucket_name = 'some-private-bucket'
#bucket_name = 'bucket-to-check'
bucket = s3.Bucket(bucket_name)
def check_bucket(bucket):
try:
s3.meta.client.head_bucket(Bucket=bucket_name)
print("Bucket Exists!")
return True
except botocore.exceptions.ClientError as e:
# If a client error is thrown, then check that it was a 404 error.
# If it was a 404 error, then the bucket does not exist.
error_code = int(e.response['Error']['Code'])
if error_code == 403:
print("Private Bucket. Forbidden Access!")
return True
elif error_code == 404:
print("Bucket Does Not Exist!")
return False
check_bucket(bucket)
希望这有助于像我这样的新手进入 boto3。
使用查找函数 -> 如果存储桶存在则返回无
if s3.lookup(bucketName) is None:
bucket=s3.create_bucket(bucketName) # Bucket Don't Exist
else:
bucket = s3.get_bucket(bucketName) #Bucket Exist
你可以使用 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)
引用http://boto.readthedocs.org/en/latest/s3_tut.html上的文档
从 Boto v2.25.0 开始,它现在执行 HEAD 请求(成本更低但错误消息更严重)。