Search code examples
pythonamazon-web-servicesamazon-s3boto3

AWS boto3 error 'IllegalLocationConstraintException'


I'm getting this error - 'IllegalLocationConstraintException' 'The me-central-1' location constraint is incompatible for the region specific endpoint this request was sent to' issue when trying to access object using presigned-url. I have created bucket to the location ('me-central-1') and file gets uploaded then I try to access it using presigned-url it throws error, So I decided to test it again by creating another bucket in ('ap-south-1') and generated presigned-url and tried to access it and it works. I still don't get what's the issue causing Location errors when accessing the object in bucket in middle east. The endpoint to be correct to https://s3.me-central-1.amazonaws.com .

Below is my python code:

def save_to_s3_bucket(file, file_name):
try:
    import base64,json
    import requests
    from io import BytesIO
    from botocore.exceptions import ClientError
    from botocore.config import Config

    format, imgstr = file.split(';base64,')

    s3 = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
                        aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4'), 
                        region_name=settings.AWS_DEFAULT_REGION)
    

    random_path = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))

    s3.put_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key='pvt/doc/ln-app/'+random_path+'/'+file_name, Body=base64.b64decode(imgstr), StorageClass='REDUCED_REDUNDANCY')

    img_url = settings.AWS_BUCKET_URL+'pvt/doc/ln-app/'+random_path+'/'+file_name
    
    url = s3.generate_presigned_url('get_object', Params = {'Bucket': settings.AWS_STORAGE_BUCKET_NAME, 'Key': 'pvt/doc/ln-app/'+random_path+'/'+file_name}, ExpiresIn = 10000)

    print('AWS-S3-URL--->>>>>>>>>', url)

    res = {
        'hasError': False,
        'message': 'Success',
        'response': {
            'key': 'pvt/doc/ln-app/'+random_path+'/'+file_name,
            'file_url': url
        }
    }
    return res
except Exception as e:
    res = {
        'hasError': True,
        'message': str(e),
        'response': None
    }
    return res

Solution

  • It's fixed. just need to add endpoint_url. For all AWS Regions launched after March 20, 2019 you need to specify the endpoint-url and AWS Region with the request. For a list of all the Amazon S3 Regions and endpoints. For reference : https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints

    s3 = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
                            aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, config=Config(signature_version='s3v4'),
                              region_name=settings.AWS_DEFAULT_REGION, endpoint_url=settings.AWS_BUCKET_ENDPOINT_URL)