SaturnFromTitan
SaturnFromTitan

Reputation: 1734

Python boto3: receive versionId after uploading a file to S3

I want to upload a file to a version-enabled S3 bucket and need its version number. Ideally, without a separate API call to avoid any possibility of a race condition. I'm using the following code snippet for upload (which is working fine):

s3 = boto3.client("s3")
s3.upload_fileobj(file_handle, bucket_name, key)

The response of this function is None and I can't really see how it is defined in boto3, so it's hard to dive any deeper into it.

The official S3 documentation mentions that the version id is included in the header of the response after upload. However, I can't see how I can access this header with boto3.

Is this possible at all? If yes: how? If no: How can I hack boto3 so I can access this response header?

Fyi, I'm using boto3==1.9.64

Thanks for your help!

EDIT: Here the link to S3 documentation that talks about the x-amz-version-id header

Upvotes: 3

Views: 2213

Answers (2)

Harshad Vyawahare
Harshad Vyawahare

Reputation: 608

I was doing s3 to s3 copy, and hence did not want to use put_object. For anyone else who is fine with making an extra call to get the versionId, can use the code below:

s3_client = boto3.client('s3')
version_id:str = s3_client.head_object(
    Bucket='bucket-name', Key='key'
)['VersionId']

Upvotes: 3

jarmod
jarmod

Reputation: 78573

You can use put_object with file-like objects. It returns VersionId in the response dictionary.

Upvotes: 3

Related Questions