问题描述
我需要使用 Boto3 从 S3 获取项目列表,但不是返回默认排序顺序(降序),我希望它通过反向顺序返回它.
I need to fetch a list of items from S3 using Boto3, but instead of returning default sort order (descending) I want it to return it via reverse order.
我知道你可以通过 awscli 做到:
I know you can do it via awscli:
aws s3api list-objects --bucket mybucketfoo --query "reverse(sort_by(Contents,&LastModified))"
并且可以通过 UI 控制台执行(不确定这是在客户端还是服务器端完成)
and its doable via the UI console (not sure if this is done client side or server side)
我似乎无法在 Boto3 中看到如何做到这一点.
I cant seem to see how to do this in Boto3.
我目前正在获取所有文件,然后进行排序……但这似乎有点矫枉过正,尤其是当我只关心 10 个左右的最新文件时.
I am currently fetching all the files, and then sorting...but that seems overkill, especially if I only care about the 10 or so most recent files.
过滤系统似乎只接受 s3 的前缀,没有别的.
The filter system seems to only accept the Prefix for s3, nothing else.
推荐答案
我对@helloV 在下面发布的内容做了一些小改动.它不是 100% 最佳,但它完成了工作,但目前 boto3 存在限制.
I did a small variation of what @helloV posted below. its not 100% optimum, but it gets the job done with the limitations boto3 has as of this time.
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]
这篇关于Boto3 S3,按上次修改对桶进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!