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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26871884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:06:16  来源:igfitidea点击:

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

pythonamazon-web-servicesamazon-s3boto3

提问by Daniel

For example, I have this code:

例如,我有这个代码:

import boto3

s3 = boto3.resource('s3')

bucket = s3.Bucket('my-bucket-name')

# Does it exist???

采纳答案by Daniel

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:

在撰写本文时,还没有高级方法来快速检查存储桶是否存在以及您是否有权访问它,但是您可以对 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.

Alternatively, you can also call create_bucketrepeatedly. 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:

或者,您也可以create_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, metawas a Python dictionary.

注意:在 0.0.7 版本之前,meta是一个 Python 字典。

回答by helloV

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

回答by vim

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 请求(成本更低但错误消息更糟)。

回答by Jacob Oommen

Use lookup Function -> Returns None if bucket Exist

使用查找函数 -> 如果桶存在则返回 None

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

回答by mondnom

I tried Daniel'sexample and it was really helpful. Followed up the boto3 documentation and here is my clean test code. I have added a check for '403' error when buckets are private and return a 'Forbidden!' error.

我尝试了丹尼尔的例子,它真的很有帮助。跟进 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)

Hope this helps some new into boto3 like me.

希望这可以帮助像我这样的新手进入 boto3。

回答by href_

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