从Google Cloud Storage中的桶内文件夹获取所有键

1 投票
1 回答
512 浏览
提问于 2025-04-18 15:16

我需要一些帮助,想从Google Cloud Storage的一个桶(bucket)里的一个文件夹中获取所有的对象(键)。目前,我在用Python执行以下代码:

GOOGLE_STORAGE = 'gs'
src_uri = boto.storage_uri(base_bucket_name + '/' + userid, GOOGLE_STORAGE)

print 'this is the src_uri: %s' % src_uri

for key in src_uri.get_all_keys():
  print 'this is the key: %s' % key

然后它返回了:

this is the src_uri: gs://basebucket/user2
this is the key: <Key: basebucket,user1/key1>
this is the key: <Key: basebucket,user1/key2>
this is the key: <Key: basebucket,user1/key3>
this is the key: <Key: basebucket,user1/key4>

结果是返回了桶里所有的键。虽然可以手动过滤掉属于其他用户的键,但这样做不太方便,也不够高效,肯定有更好的方法。请告诉我你是否有过类似的经验。

1 个回答

1

如果你查看一下 get_all_keys 的文档,你会发现需要传入 prefixdelimiter 这两个参数。

不过,我建议你使用 list 函数,这样做可能会更好。你可以试试下面这样的代码:

bucket_uri = boto.storage_uri(base_bucket_name, GOOGLE_STORAGE)
for object_uri in bucket_uri.list_bucket(prefix='/%s' % userid, delimiter='/'):
    print object_uri

撰写回答