Skip to main content
 首页 » 编程设计

python之如何将谷歌云存储中的文件打开到云函数中

2024年12月31日9yyy_WW

以下是我通常如何将 GCS 文件下载到本地:

storage_client = storage.Client() 
bucket = storage_client.get_bucket('mybucket') 
blob = bucket.blob('myBigFile.txt') 
blob.download_to_filename('myBigFile.txt) 

我正在处理的文件比 Cloud Functions 允许的大小/内存大得多(例如,几 GB 到几 TB),因此以上内容不适用于这些大文件。

是否有更简单的“流式”(参见下面的示例 1)或“直接访问”(参见下面的示例 2)方式来处理 Cloud Functions 中的 GCS 文件?

我想要做的两个例子是:

# 1. Load it in chunks of 5GB -- "Streaming" 
storage_client = storage.Client() 
bucket = storage_client.get_bucket('mybucket') 
blob = bucket.blob('myBigFile.txt') 
while True: 
    data = blob.download_to_filename('myBigFile.txt', chunk_size=5GB) 
    do_something(data) 
    if not data: break 

或者:

# 2. Read the data from GCS without downloading it locally -- "Direct Access" 
storage_client = storage.Client() 
bucket = storage_client.get_bucket('mybucket') 
blob = bucket.blob('myBigFile.txt') 
with blob.read_filename('myBigFile.txt') as f: 
    do_something(f) 

我不确定这些是否可行,但我留下了一些关于如何工作的选项。好像是 Streaming Option受支持,但我不确定如何将其应用于上述情况。

请您参考如下方法:

您可能可以使用 Cloud Storage XML API 实现接近您的 #1 示例的效果.

在 Cloud Functions 中实现它应该没有问题,因为它完全基于标准 HTTP 请求。

您可能正在寻找 GET Object请求 Download an Object :

GET requests for objects can include a Range header as defined in the HTTP 1.1 RFC to limit the scope of the returned data within the object, but be aware that in certain circumstances the range header is ignored.

HTTP Range header 似乎可用于实现您正在寻找的“ block ”(但作为独立请求,而不是“流”模式):

The range of bytes that you want returned in the response, or the range of bytes that have been uploaded to the Cloud Storage system.

Valid Values

Any contiguous range of bytes.

Example

Range: bytes=0-1999 (first 2000 bytes)

Range: bytes=-2000 (last 2000 bytes)

Range: bytes=2000- (from byte 2000 to end of file)

Implementation Details

Cloud Storage does not handle complex disjoint ranges, but it does support simple contiguous byte ranges. Also, byte ranges are inclusive; that is, bytes=0-999 represent the first 1000 bytes in a file or object. A valid and successful request will result in a 206 Partial Content response code. For more information, see the specification.

由于范围是静态的,因此您不太可能找到完全适合的范围值以使 block 与存储的数据“边界”完美匹配。因此,您可能需要选择稍微重叠的 block ,以便能够捕获数据,否则这些数据将被分成 2 个 block 。

注意:我没有尝试这个,答案完全基于文档。