0
votes

I have written code on my backend (hosted on Elastic Beanstalk) to retrieve a file from an S3 bucket and save it back to the bucket under a different name. I am using boto3 and have created an s3 client called 's3'.

bucketname is the name of the bucket, keyname is name of the key. I am also using the tempfile module

tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, 'wb') as f:
    s3.download_fileobj(bucketname, keyname, f)    
s3.upload_file(tmp, bucketname, 'fake.jpg')

I was wondering if my understanding was off (still debugging why there is an error) - I created a tempfile and opened and saved within it the contents of the object with the keyname and bucketname. Then I uploaded that temp file to the bucket under a different name. Is my reasoning correct?

1
Getting any errors? - Marcin

1 Answers

1
votes

The upload_file() command is expecting a filename (as a string) in the first parameter, not a file object.

Instead, you should use upload_fileobj().

However, I would recommend something different...

If you simply wish to make a copy of an object, you can use copy_object:

response = client.copy_object(
    Bucket='destinationbucket',
    CopySource='/sourcebucket/HappyFace.jpg',
    Key='HappyFaceCopy.jpg',
)