首页 > 解决方案 > Python boto3 检查区域内的有效存储桶

问题描述

我已经看到了检查 S3 存储桶是否存在的示例,并在下面实现了它们。我的存储桶位于 us-east-1 区域,但以下代码不会引发异常。有没有办法根据我的会话使检查区域特定?

session = boto3.Session(
    profile_name = 'TEST'
    ,region_name='ap-south-1'
)

s3 = session.resource('s3')

bucket_name = 'TEST_BUCKET'

try:
    s3.meta.client.head_bucket(Bucket = bucket_name)
except ClientError as c:
    print(c)

标签: pythonpython-3.xamazon-web-servicesamazon-s3boto3

解决方案


您将请求发送到哪个 S3 区域端点并不重要。底层 SDK (boto3) 将根据需要重定向。但是,如果您事先知道正确的区域,则最好定位到正确的区域,以节省重定向。

如果您在调试模式下使用 awscli,您可以看到详细信息:

aws s3api head-bucket --bucket mybucket --region ap-south-1 --debug

您将看到与此类似的调试输出:

DEBUG - S3 client configured for region ap-south-1 but the bucket mybucket is in region us-east-1; Please configure the proper region to avoid multiple unnecessary redirects and signing attempts.
DEBUG - Switching signature version for service s3 to version s3v4 based on config file override.
DEBUG - Updating URI from https://s3.ap-south-1.amazonaws.com/mybucket to https://s3.us-east-1.amazonaws.com/mybucket

请注意,awscli 使用 boto3 SDK,您的 Python 脚本也是如此。


推荐阅读