2017-06-15 47 views
4

我需要使用Boto3从S3中获取项目列表,但不是返回默认排序顺序(降序),而是希望它通过相反的顺序返回。Boto3 S3,按最后修改的排序桶

我知道你可以通过awscli做到这一点:

aws s3api list-objects --bucket mybucketfoo --query "reverse(sort_by(Contents,&LastModified))" 

,并通过UI控制台其可行的(不知道这是做客户端或服务器端)

我似乎怎么看在Boto3中做到这一点。

我目前正在抓取所有的文件,然后排序......但似乎矫枉过正,尤其是如果我只关心10个左右的最新文件。

过滤器系统似乎只接受s3的前缀,没有别的。

+0

您可以获取所有对象,获取其最后修改日期并根据日期对其进行排序。看看这个[问题](https://stackoverflow.com/questions/9679344/how-can-i-get-last-modified-datetime-of-s3-objects-with-boto) – cookiedough

+0

S3 api不支持以这种方式列出。 CLI(也可能是控制台)将获取所有内容,然后执行排序。 –

+0

您正在将数据返回到Python,因此只需对返回的数据进行排序即可。没有必要问boto3为你做 - 这只是一个额外的Python。 –

回答

1

我做什么@helloV贴在下面的微小变化。它不是100%的最佳选择,但它完成了boto3迄今为止的局限性。

s3 = boto3.resource('s3') 
my_bucket = s3.Bucket('myBucket') 
unsorted = [] 
for file in my_bucket.objects.filter(): 
    unsorted.append(file) 

files = [obj.key for obj in sorted(unsorted, key=get_last_modified, 
    reverse=True)][0:9] 
1

我可以理解你的用例。你可以通过aws s3命令轻松完成。

例如: AWS S3 LS testing1-goreplay --recursive

让我知道它是否适合你。

2

如果存储桶中没有多个对象,则可以使用Python将其排序以满足您的需要。

定义拉姆达拿到最后修改时间:

get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s')) 

获取所有对象,并通过最后修改时间进行排序。

s3 = boto3.client('s3') 
objs = s3.list_objects_v2(Bucket='my_bucket')['Contents'] 
[obj['Key'] for obj in sorted(objs, key=get_last_modified)] 

如果要反转排序:

[obj['Key'] for obj in sorted(objs, key=get_last_modified, reverse=True)] 
+0

我做的这个变化......虽然没有什么,我认为这是最佳的: 'get_last_modified =拉姆达OBJ:INT(obj.last_modified.strftime( '%s' 的))' '文件= [OBJ。键排序(未排序,键= get_last_modified,reverse = True)] [0:9] – nate