AWS boto3 无法创建存储桶 - Python

问题描述 投票:0回答:1

我面临一个问题,我的代码无法使用 boto3 python 在 AWS 中成功创建存储桶。下面是我的代码

import boto3
s3 = boto3.resource('s3')

def create_bucket(bucket_name, region='us-east-1'):
    if region is None:
        s3.create_bucket(Bucket=bucket_name)
    else:
        location = { 'LocationConstraint': region }
        s3.create_bucket(Bucket=bucket_name,
                         CreateBucketConfiguration=location)

create_bucket('my-testing-bucket')

当我运行时,我收到此错误

botocore.exceptions.ClientError: An error occurred (IllegalLocationConstraintException) when calling the CreateBucket operation: The us-east-1 location constraint is incompatible for the region specific endpoint this request was sent to.
。将很高兴得到您的帮助。谢谢

我想使用 boto3 python 在 AWS S3 中创建一个存储桶。但我的代码有错误

python-3.x amazon-web-services amazon-s3 boto3
1个回答
0
投票

有几个问题:

  • 创建存储桶时,boto3 客户端需要连接到创建存储桶的同一区域。因此,在创建 S3 客户端时,您需要传递
    region_name
  • region
    函数中
    create_bucket()
    参数的默认值将传递值
    'us-east-1'
    ,因此
    region
    永远不会为空

这是一些更新的代码:

import boto3

region = 'us-east-1'

s3 = boto3.resource('s3', region_name=region)

def create_bucket(bucket_name, region='us-east-1'):
    if region == 'us-east-1':
        s3.create_bucket(Bucket=bucket_name)
    else:
        location = { 'LocationConstraint': region }
        s3.create_bucket(Bucket=bucket_name,
                         CreateBucketConfiguration=location)

create_bucket('my-new-bucket')
© www.soinside.com 2019 - 2024. All rights reserved.