我有一个要在 GCS 中检查的文件路径列表。看起来像这样:
for path in all_paths:
try:
gcs.blob(GCS_BUCKET_NAME, path).exists()
except google.api_core.exceptions.NotFound:
missing_paths.append(path)
这工作正常,但需要花费很多时间,因为每个路径的请求都是一一发送的。有没有办法在谷歌云存储API中发送批量请求?或者有什么办法可以加快这个检查速度?
使用 Cloud Storage,您只能按路径前缀 (path/to/file.xxx) 进行过滤。然后您将收到与此前缀匹配的所有文件,甚至是子路径(path/to/sub/path/file.xxx)。所以剩下的处理就靠你们自己来完成了。
是的,如果您有很多文件,这将花费很多时间。
这有点棘手,因为您需要发出一批延迟的请求,然后解析响应。 google.cloud.storage python API 有一种使用上下文管理器对请求进行批处理的方法,但响应存储在隐藏变量中,没有 getter 方法或公共属性。
所以现在,这有效:
from google.cloud.storage import Client
cl = Client()
bucket = cl.get_bucket("<enter bucket name>")
filenames = ["<enter>", "<file>", "<names>"]
blobs = [bucket.blob(f) for f in filenames]
with cl.batch(raise_exception=False) as b:
[blob.exists() for blob in blobs]
exists = [resp.status_code==200 for resp in b._responses]
因为
_responses
是私有的,所以在小的软件包更新中可能容易发生变化。
您可能还想添加对其他状态代码的处理,并添加重试策略。您可以将 200 解释为“存在”,将 404 解释为“不存在”。