简体   繁体   English

如何轻松确定Boto 3 S3存储桶资源是否存在?

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

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. 在撰写本文时,没有高级方法可以快速检查存储桶是否存在并且您可以访问它,但是您可以对HeadBucket操作进行低级调用。 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. 或者,您也可以重复调用create_bucket 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. 注意:在0.0.7版本之前, meta是一个Python字典。

As mentioned by @Daniel, the best way as suggested by Boto3 docs is to use head_bucket() 正如@Daniel所提到的,Boto3文档建议的最佳方法是使用head_bucket()

head_bucket() - This operation is useful to determine if a bucket exists and you have permission to access it . head_bucket() - 此操作可用于确定存储桶是否存在且您是否有权访问存储桶

If you have a small number of buckets, you can use the following: 如果您有少量存储桶,则可以使用以下命令:

>>> import boto3
>>> s3 = boto3.resource('s3')
>>> s3.Bucket('Hello') in s3.buckets.all()
False
>>> s3.Bucket('some-docs') in s3.buckets.all()
True
>>> 

I tried Daniel's example and it was really helpful. 我试过丹尼尔的例子,这真的很有帮助。 Followed up the boto3 documentation and here is my clean test code. 跟进了boto3文档,这是我的干净测试代码。 I have added a check for '403' error when buckets are private and return a 'Forbidden!' 当存储桶是私有的并且返回'禁止'时,我已经添加了对'403'错误的检查 error. 错误。

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)

Hope this helps some new into boto3 like me. 希望这有助于像我一样进入boto3。

I've had success with this: 我在这方面取得了成功:

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")

Use lookup Function -> Returns None if bucket Exist 如果存在桶,则使用查找功能 - >返回无

if s3.lookup(bucketName) is None:
    bucket=s3.create_bucket(bucketName) # Bucket Don't Exist
else:
    bucket = s3.get_bucket(bucketName) #Bucket Exist

you can use conn.get_bucket 你可以使用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 引用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). 从Boto v2.25.0开始,现在执行HEAD请求(更便宜但更糟糕的错误消息)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查AWS S3存在桶? - How can I check that a AWS S3 bucket exists? 如何使用 boto3 将 Github 上的文件上传到 AWS S3 存储桶? - How can I upload the files on Github to AWS S3 bucket using boto3? 如何检查 S3 存储桶中的对象在 boto3 中是否公开? - How can I check if an object in an S3 bucket is public or not in boto3? boto的get_resource_type('s3')。Object(bucket_name,key)是否可以使用通配符? - Can boto's get_resource_type('s3').Object(bucket_name, key) take wildcards? 使用 boto3 检查 s3 中的存储桶中是否存在密钥 - check if a key exists in a bucket in s3 using boto3 如何将子文件夹移动到同一个 s3 存储桶 boto3 中的另一个主文件夹? - How can I move a sub-folder to another main folder within same s3 bucket boto3? 如何使用 boto3 仅使用 python 将更改的文件从一个 S3 存储桶复制到另一个存储桶? - How can I copy only changed files from one S3 Bucket to another one with python using boto3? 使用boto库,我可以避免在S3中对基本存储桶授予列表权限吗? - With the boto library, can I avoid granting list permissions on a base bucket in S3? 将文件从 databricks dbfs / local 上传到 S3 存储桶。 如何使用 boto3 库或挂载 s3 将文件从 databricks 上传到 S3 存储桶? - Uploading a file from databricks dbfs / local to an S3 bucket. How do i upload a file from databricks to S3 bucket using boto3 library or mounting s3? 如何使用 python (boto3) 连接到带有 pem 文件的 Amazon S3 存储桶 - How do I connect to an Amazon S3 bucket with a pem file using python (boto3)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM