'Boto3 throws exception when uploading file but the file is saved in S3

I need to upload files using boto3 with Flask. I have the following method to upload the files and I want to return the path of the file within S3.

utils.py

import io
import boto3
from app import app

s3 = boto3.client(
    "s3",
    aws_access_key_id = app.config['S3_KEY'],
    aws_secret_access_key = app.config['S3_SECRET']
)

def upload_file(file, bucket_name, acl=app.config['AWS_DEFAULT_ACL']):
    try:
        s3.upload_fileobj(
            file,
            bucket_name,
            f"Profile_Photos/{file.filename}",
            ExtraArgs = {
                "ACL": 'private',
                "ContentType": file.content_type
            }
        )       

        return "{}{}".format(app.config['S3_LOCATION', file.filename])  

    except Exception as e:
        print("Something was wrong: ", e) # This exception is thrown
        return e

Inside the main class I have the following:

main.py

@app.route('/registro', methods=['POST'])
def register():
    conn = None
    cursor = None
    try:                 
        username= request.form.get('user', None)
        password = request.form.get('password', None)

        if username and password:
            hashed_password = hashlib.md5(password.encode()).hexdigest()
            sql = "INSERT INTO Users(username, password) VALUES (%s, %s)"
            data = (username, hashed_password)            
            conn = mySQL.connect()
            cursor = conn.cursor()
            cursor.execute(sql, data)            
            conn.commit()        

            if 'current_photo' in request.files:
                file = request.files['current_photo']
                if file.filename != '':
                    file_name = os.path.splitext(file.filename)[0]
                    extension = file.filename.split('.')[-1]
                    new_name = "{}_{}.{}".format(file_name, username, extension)
                    file.filename = new_name
                    file.filename = secure_filename(file.filename)
                    print("Before")
                    path = upload_file(file, app.config['S3_BUCKET']) # Error occurs here
                    print("After")                 


            res = jsonify('User created.')
            res.status_code = 200            
            return res                    
    except Exception as e:
        print(e)        
        return 'Error'    

if __name__ == '__main__':
    app.run()

The problem is that when executing the code, an exception is always thrown in the upload_file method, however the photo is uploaded to S3. The message doesn't seem very informative:

Something was wrong ('S3_LOCATION', 'profile_user2.jpg').

What does that message mean and why is the exception being thrown?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source