简答:
-
使用Delimiter='/'。这避免了对您的存储桶进行递归列表。这里的一些答案错误地建议进行完整列表并使用一些字符串操作来检索目录名称。这可能是非常低效的。请记住,S3 实际上对存储桶可以包含的对象数量没有限制。所以,想象一下,在bar/ 和foo/ 之间,你有一万亿个对象:你会等待很长时间才能得到['bar/', 'foo/']。
-
使用Paginators。出于同样的原因(S3 是工程师对无穷大的近似值),您必须逐页列出并避免将所有列表存储在内存中。相反,将您的“lister”视为一个迭代器,并处理它产生的流。
-
使用boto3.client,而不是boto3.resource。 resource 版本似乎不能很好地处理 Delimiter 选项。如果你有资源,比如bucket = boto3.resource('s3').Bucket(name),你可以通过bucket.meta.client获取对应的客户端。
长答案:
以下是我用于简单存储桶的迭代器(无版本处理)。
import os
import boto3
from collections import namedtuple
from operator import attrgetter
S3Obj = namedtuple('S3Obj', ['key', 'mtime', 'size', 'ETag'])
def s3list(bucket, path, start=None, end=None, recursive=True, list_dirs=True,
list_objs=True, limit=None):
"""
Iterator that lists a bucket's objects under path, (optionally) starting with
start and ending before end.
If recursive is False, then list only the "depth=0" items (dirs and objects).
If recursive is True, then list recursively all objects (no dirs).
Args:
bucket:
a boto3.resource('s3').Bucket().
path:
a directory in the bucket.
start:
optional: start key, inclusive (may be a relative path under path, or
absolute in the bucket)
end:
optional: stop key, exclusive (may be a relative path under path, or
absolute in the bucket)
recursive:
optional, default True. If True, lists only objects. If False, lists
only depth 0 "directories" and objects.
list_dirs:
optional, default True. Has no effect in recursive listing. On
non-recursive listing, if False, then directories are omitted.
list_objs:
optional, default True. If False, then directories are omitted.
limit:
optional. If specified, then lists at most this many items.
Returns:
an iterator of S3Obj.
Examples:
# set up
>>> s3 = boto3.resource('s3')
... bucket = s3.Bucket('bucket-name')
# iterate through all S3 objects under some dir
>>> for p in s3list(bucket, 'some/dir'):
... print(p)
# iterate through up to 20 S3 objects under some dir, starting with foo_0010
>>> for p in s3list(bucket, 'some/dir', limit=20, start='foo_0010'):
... print(p)
# non-recursive listing under some dir:
>>> for p in s3list(bucket, 'some/dir', recursive=False):
... print(p)
# non-recursive listing under some dir, listing only dirs:
>>> for p in s3list(bucket, 'some/dir', recursive=False, list_objs=False):
... print(p)
"""
kwargs = dict()
if start is not None:
if not start.startswith(path):
start = os.path.join(path, start)
# note: need to use a string just smaller than start, because
# the list_object API specifies that start is excluded (the first
# result is *after* start).
kwargs.update(Marker=__prev_str(start))
if end is not None:
if not end.startswith(path):
end = os.path.join(path, end)
if not recursive:
kwargs.update(Delimiter='/')
if not path.endswith('/'):
path += '/'
kwargs.update(Prefix=path)
if limit is not None:
kwargs.update(PaginationConfig={'MaxItems': limit})
paginator = bucket.meta.client.get_paginator('list_objects')
for resp in paginator.paginate(Bucket=bucket.name, **kwargs):
q = []
if 'CommonPrefixes' in resp and list_dirs:
q = [S3Obj(f['Prefix'], None, None, None) for f in resp['CommonPrefixes']]
if 'Contents' in resp and list_objs:
q += [S3Obj(f['Key'], f['LastModified'], f['Size'], f['ETag']) for f in resp['Contents']]
# note: even with sorted lists, it is faster to sort(a+b)
# than heapq.merge(a, b) at least up to 10K elements in each list
q = sorted(q, key=attrgetter('key'))
if limit is not None:
q = q[:limit]
limit -= len(q)
for p in q:
if end is not None and p.key >= end:
return
yield p
def __prev_str(s):
if len(s) == 0:
return s
s, c = s[:-1], ord(s[-1])
if c > 0:
s += chr(c - 1)
s += ''.join(['\u7FFF' for _ in range(10)])
return s
测试:
以下内容有助于测试paginator 和list_objects 的行为。它创建了许多目录和文件。由于页面最多有 1000 个条目,因此我们将其倍数用于目录和文件。 dirs 仅包含目录(每个目录都有一个对象)。 mixed 包含 dirs 和 objects 的混合,每个 dir 有 2 个对象的比例(当然,在 dir 下还有一个对象;S3 只存储对象)。
import concurrent
def genkeys(top='tmp/test', n=2000):
for k in range(n):
if k % 100 == 0:
print(k)
for name in [
os.path.join(top, 'dirs', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_foo_a'),
os.path.join(top, 'mixed', f'{k:04d}_foo_b'),
]:
yield name
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
executor.map(lambda name: bucket.put_object(Key=name, Body='hi\n'.encode()), genkeys())
得到的结构是:
./dirs/0000_dir/foo
./dirs/0001_dir/foo
./dirs/0002_dir/foo
...
./dirs/1999_dir/foo
./mixed/0000_dir/foo
./mixed/0000_foo_a
./mixed/0000_foo_b
./mixed/0001_dir/foo
./mixed/0001_foo_a
./mixed/0001_foo_b
./mixed/0002_dir/foo
./mixed/0002_foo_a
./mixed/0002_foo_b
...
./mixed/1999_dir/foo
./mixed/1999_foo_a
./mixed/1999_foo_b
稍微修改上面为s3list 提供的代码以检查来自paginator 的响应,您可以观察到一些有趣的事实:
-
Marker 真的是独一无二的。给定Marker=topdir + 'mixed/0500_foo_a' 将使列表在该键之后开始(根据AmazonS3 API),即.../mixed/0500_foo_b。这就是__prev_str() 的原因。
-
使用Delimiter,在列出mixed/ 时,来自paginator 的每个响应都包含666 个键和334 个公共前缀。它非常擅长不产生大量响应。
-
相比之下,当列出 dirs/ 时,来自 paginator 的每个响应都包含 1000 个公共前缀(并且没有键)。
-
通过PaginationConfig={'MaxItems': limit} 形式的限制仅限制键的数量,而不限制公共前缀。我们通过进一步截断迭代器的流来处理这个问题。