How to access response from boto3 bucket.put_object?

Viewed 1539

Looking at the boto3 docs, I see that client.put_object has a response shown, but I don't see a way to get the response from bucket.put_object.

Sample snippet:

        s3 = boto3.resource(
                's3',
                aws_access_key_id=redacted,
                aws_secret_access_key=redacted,
        )

        s3.Bucket(bucketName).put_object(Key="bucket-path/" + fileName, Body=blob, ContentMD5=md5Checksum)

        logging.info("Uploaded to S3 successfully")

How is this accomplished?

2 Answers

put_object returns S3.Object, which in turn has the wait_until_exists method.

Therefore, something along these lines should be sufficient (my verification code is bellow):

import boto3

s3 = boto3.resource('s3')

with open('test.img', 'rb') as f:

    obj = s3.Bucket('test-ssss4444').put_object(
            Key='fileName', 
            Body=f)
    
obj.wait_until_exists() # optional

print("Uploaded to S3 successfully")

put_object is a blocking operation. Thus it will block your program until your file is uploaded. Therefore wait_until_exists is not really needed. But if you want to make sure that the upload actually went through and the object is in S3 you can use it.

You have to use boto3.client instead of boto3.resource to get the response information like ETag and etc. It has a little bit different syntax.

import boto3

s3 = boto3.resource('s3')
s3.put_object(Bucket='bucket-name', Key='fileName', Body=body)
Related