lon*_*ony 3 amazon-s3 amazon-web-services 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"])
Run Code Online (Sandbox Code Playgroud)
s3 = boto3.client("s3", region_name="eu-west-1")
Run Code Online (Sandbox Code Playgroud)
连接到中的S3 API端点eu-west-1。它不会将清单限制为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"])
Run Code Online (Sandbox Code Playgroud)
如果您需要使用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)
Run Code Online (Sandbox Code Playgroud)
上述解决方案并不总是适用于美国某些地区的存储桶,因为“LocationConstraint”可以为空。这是另一个解决方案:
s3 = boto3.client("s3")
for bucket in s3.list_buckets()["Buckets"]:
if s3.head_bucket(Bucket=bucket['Name'])['ResponseMetadata']['HTTPHeaders']['x-amz-bucket-region'] == 'us-east-1':
print(bucket["Name"])
Run Code Online (Sandbox Code Playgroud)
SDK方法:
s3.head_bucket(Bucket=[INSERT_BUCKET_NAME_HERE])['ResponseMetadata']['HTTPHeaders']['x-amz-bucket-region']
... 应该总是给你桶区域。感谢 sd65 的提示:https : //github.com/boto/boto3/issues/292
| 归档时间: |
|
| 查看次数: |
1800 次 |
| 最近记录: |