所以我有这个Python代码来创建一个s3存储桶:
import boto3
from botocore.exceptions import ClientError
def create_bucket(bucket, secret):
s3 = boto3.Session(
region_name="my-region-1",
aws_access_key_id=secret["aws_access_key_id"],
aws_secret_access_key=secret["aws_secret_access_key"]
)
try:
response = s3.create_bucket(
ACL="private",
Bucket=bucket,
CreateBucketConfiguration={
'LocationConstraint': 'my-region-1'
}
)
except ClientError:
return None
return response["Location"]
print(create_bucket("bucketname", secret))
它应该在
my-region-1
中创建存储桶,但我得到的输出是 /bucketname
而不是存储桶 URL (http://bucketname.s3.my.domain.name
)。 This手册意味着我的代码是正确的(在示例部分中有我的用例),如果我提供'LocationConstraint': 'my-region-1'
,则应该打印URL,但我得到了另一个示例的结果(没有提供的示例)位置限制)。
我有什么遗漏的吗?
我做了一些实验,发现示例是准确的,但缺少一条信息。
第一个例子
response = client.create_bucket(
Bucket='examplebucket',
CreateBucketConfiguration={
'LocationConstraint': 'eu-west-1',
},
)
print(response)
预期输出:
{
'Location': 'http://examplebucket.s3.amazonaws.com/',
'ResponseMetadata': {
'...': '...',
},
}
其工作原理如文档中所示。
LocationConstraint
指定应在其中创建存储桶的Region。它返回 Location
作为 URL(如上所示)。
第二个例子
response = client.create_bucket(
Bucket='examplebucket',
)
print(response)
预期输出:
{
'Location': '/examplebucket',
'ResponseMetadata': {
'...': '...',
},
}
此示例仅适用于
us-east-1
区域。它似乎与“原始”S3 向后兼容(在存在多个区域之前)。 Location
以斜线形式返回,后跟存储桶名称。该代码对于其他区域失败,指出:
未指定的位置约束与此请求发送到的区域特定端点不兼容。