我已经看到了检查 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/