Boto3只获得特定区域的S3桶

时间:2018-04-13 09:54:55

标签: amazon-web-services amazon-s3 boto3

以下代码遗憾地列出了所有区域的所有存储桶,而不仅仅是指定的“eu-west-1”。我怎么能改变它?

import boto3

s3 = boto3.client("s3", region_name="eu-west-1")

for bucket in s3.list_buckets()["Buckets"]:

    bucket_name = bucket["Name"]
    print(bucket["Name"])

2 个答案:

答案 0 :(得分:4)

s3 = boto3.client("s3", region_name="eu-west-1")

连接到eu-west-1中的S3 API端点。它不会将列表限制为eu-west-1桶。一种解决方案是查询存储桶位置和过滤器。

s3 = boto3.client("s3")

for bucket in s3.list_buckets()["Buckets"]:
    if s3.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint'] == 'eu-west-1':
        print(bucket["Name"])

如果你需要一个使用Python列表理解的单行程序:

region_buckets = [bucket["Name"] for bucket in s3.list_buckets()["Buckets"] if s3.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint'] == 'eu-west-1']
print(region_buckets)

答案 1 :(得分:2)

由于“ LocationConstraint”可以为null,因此上述解决方案在美国某些地区并非始终适用于存储分区。这是另一种解决方案:

...

SDK方法:

s3 = boto3.client("s3")

for bucket in s3.list_buckets()["Buckets"]:
    if s3.head_bucket(Bucket=first_bucket)['ResponseMetadata']['HTTPHeaders']['x-amz-bucket-region'] == 'us-east-1':
        print(bucket["Name"])

...应该始终为您提供存储分区。感谢sd65的提示:https://github.com/boto/boto3/issues/292