Search code examples
pythonamazon-s3boto3

Boto3 presigned_url does not generate a valid url with region


I'm using the code belwo to generate a presigned url but the url I'm getting does not contain the region I configured for s3 client.

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

And before you ask, yes bucket is in region.

I have removed region : link didn't work I added region to link manually: new link didn't work I defined the clinet in the function: didn't work

I keep getting IllegalLocationConstraintException Error.

When I was uploading the file I got this error then I added the region to s3 client configuration and problem solved but here I don't know why it's not working.


Solution

  • You need to supply the region-specific endpoint when creating the boto3 client, as follows:

    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'
    )