Python boto3 检查区域内的有效存储桶

标签 python python-3.x amazon-web-services amazon-s3 boto3

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

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)

最佳答案

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

如果您在 Debug模式下使用 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 脚本也是如此。

关于Python boto3 检查区域内的有效存储桶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64850820/

相关文章:

python - 如何在pytorch中求偏导数

python - 如何改进此 python 代码以改进负面测试?

amazon-web-services - 在 AWS EC2 上,我无法进行 wget 或 curl 或任何出站连接

python - AWS lambda : Variable value from one execution is preserved and used by subsequent run

python - Pyldap(使用 Django Auth LDAP)安装在 python3 virtualenv 中

python - 从 tox.ini 确定所需的 Python 版本并在需要时安装

python - 灵敏度特异性图 python

python - 计算一个元素在 python 列表中连续出现 n 次的次数

python-3.x - 使用 Python3 为 Kubernetes 创建 YAML

php - 带有 PHP SDK 的 AWS EC2 - 等到实例具有公共(public) DNS 名称