Boto3 presigned_url 未生成带区域的有效 url

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

我正在使用下面的代码生成预签名的 url,但我得到的 url 不包含我为 s3 客户端配置的区域。

REGION_NAME = 'me-south-1'


# Initialize S3 client
# Create the S3 client with the correct region
s3_client = boto3.client(
    "s3",
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
    region_name=REGION_NAME 
)

def upload_file(file_stream, object_name):
    """Uploads a byte stream to the specified bucket on AWS under the 'kyc/' prefix and returns the file URL."""
    
    # Add the 'kyc/' prefix to the object name
    object_name_with_prefix = f"kyc/{object_name}"
    
    try:
        s3_client.upload_fileobj(file_stream, AWS_BUCKET_NAME, object_name_with_prefix)
        print(f"File uploaded successfully as '{object_name_with_prefix}'")
        
        # Construct the file URL
        file_url = f"https://{AWS_BUCKET_NAME}.s3.me-south-1.amazonaws.com/{object_name_with_prefix}"
        return (True, file_url)
    except NoCredentialsError:
        print("Credentials not available.")
        return (False, NoCredentialsError)
    except ClientError as e:
        print("Failed to upload file:", e)
        return (False, e)



def create_presigned_url_expanded(object_name,
                                  expiration=3600):
    
    url = s3_client.generate_presigned_url(
        ClientMethod='get_object',
        Params={'Bucket': AWS_BUCKET_NAME, 'Key': object_name},
        ExpiresIn=expiration
    )

    return url

在您询问之前,是的,存储桶位于该区域。

我已删除区域:链接不起作用 我手动添加了要链接的区域:新链接不起作用 我在函数中定义了 clinet:不起作用

我不断收到 IllegalLocationConstraintException 错误。

当我上传文件时出现此错误,然后我将该区域添加到 s3 客户端配置并解决问题,但在这里我不知道为什么它不起作用。

python amazon-s3 boto3
1个回答
0
投票

您需要在创建 boto3 客户端时提供特定于区域的端点,如下所示:

REGION_NAME = 'me-south-1'

# Create the S3 client with the correct region and endpoint
s3_client = boto3.client(
    "s3",
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
    region_name=REGION_NAME,
    endpoint_url=f'https://s3.{REGION_NAME}.amazonaws.com'
)
© www.soinside.com 2019 - 2024. All rights reserved.