Dan*_*iel 32 python amazon-s3 amazon-web-services boto3
例如,我有这个代码:
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket-name')
# Does it exist???
Run Code Online (Sandbox Code Playgroud)
Dan*_*iel 54
在撰写本文时,没有高级方法可以快速检查存储桶是否存在并且您可以访问它,但是您可以对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.
Run Code Online (Sandbox Code Playgroud)
或者,您也可以create_bucket反复拨打电话.该操作是幂等的,因此它将创建或仅返回现有存储桶,如果您检查存在以了解是否应创建存储桶,这将非常有用:
bucket = s3.create_bucket(Bucket='my-bucket-name')
Run Code Online (Sandbox Code Playgroud)
一如既往,请务必查看官方文档.
注意:在0.0.7版本之前,meta是一个Python字典.
hel*_*loV 23
>>> import boto3
>>> s3 = boto3.resource('s3')
>>> s3.Bucket('Hello') in s3.buckets.all()
False
>>> s3.Bucket('some-docs') in s3.buckets.all()
True
>>>
Run Code Online (Sandbox Code Playgroud)
小智 11
我试过丹尼尔的例子,这真的很有帮助.跟进了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)
Run Code Online (Sandbox Code Playgroud)
希望这有助于像我一样进入boto3.
我已经成功地做到了:
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")
Run Code Online (Sandbox Code Playgroud)