Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use versioning in S3 with boto3?

I am using a versioned S3 bucket, with boto3. How can I retrieve all versions for a given key (or even all versions for all keys) ? I can do this:

for os in b.objects.filter(Prefix=pref):
    print("os.key")
     

but that gives me only the most recent version for each key.

like image 591
Old_Mortality Avatar asked Feb 22 '16 03:02

Old_Mortality


People also ask

Does S3 have versioning?

Versioning in Amazon S3 is a means of keeping multiple variants of an object in the same bucket. You can use the S3 Versioning feature to preserve, retrieve, and restore every version of every object stored in your buckets.

How do I connect my S3 to Boto3?

Setting up a client To access any AWS service with Boto3, we have to connect to it with a client. Here, we create an S3 client. We specify the region in which our data lives. We also have to pass the access key and the password, which we can generate in the AWS console, as described here.


1 Answers

import boto3

bucket = 'bucket name'
key = 'key'
s3 = boto3.resource('s3')
versions = s3.Bucket(bucket).object_versions.filter(Prefix=key)

for version in versions:
    obj = version.get()
    print(obj.get('VersionId'), obj.get('ContentLength'), obj.get('LastModified'))

I can't take credit as I had the same question but I found this here

like image 192
al76 Avatar answered Oct 13 '22 19:10

al76