How can I use versioning in S3 with boto3?

假装没事ソ 提交于 2021-02-18 11:44:08

问题


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.

Many thanks,


回答1:


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




回答2:


boto3 s3 client has a list_object_versions method.

resp = client.list_object_versions(Prefix=prefix, Bucket=bucket)

for obj in [*resp['Versions'], *resp.get('DeleteMarkers', [])]:
    print(f"Key: {obj['Key']}")
    print(f"VersionId: {obj['VersionId']}")
    print(f"LastModified: {obj['LastModified']}")
    print(f"IsLatest: {obj['IsLatest']}")
    print(f"Size: {obj.get('Size', 0)/1e6}")

supposing you wanted to delete all but the current version, you could do so by adding the objects where not IsLatest to a to_delete list, then running the following:

for obj in to_delete:
    print(client.delete_object(Bucket=bucket, Key=obj['Key'], VersionId=obj['VersionId']))


来源:https://stackoverflow.com/questions/35545435/how-can-i-use-versioning-in-s3-with-boto3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!