Boto3仅获得特定区域的S3存储桶 [英] Boto3 get only S3 buckets of specific region

查看:156
本文介绍了Boto3仅获得特定区域的S3存储桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码令人遗憾地列出了所有区域的所有存储桶,不仅列出了指定的"eu-west-1".我该如何更改?

The following code sadly lists all buckets of all regions and not only from "eu-west-1" as specified. How can I change that?

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

推荐答案

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

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

connects to S3 API endpoint in eu-west-1. It doesn't limit the listing to eu-west-1 buckets. One solution is to query the bucket location and filter.

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的列表理解功能的班轮:

If you need a one liner using Python's list comprehension:

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)

这篇关于Boto3仅获得特定区域的S3存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆