问题
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