繁体   English   中英

从 Google Cloud Function (Python) 将新文件写入 Google Cloud Storage 存储桶

[英]Writing a new file to a Google Cloud Storage bucket from a Google Cloud Function (Python)

我正在尝试从 Python Google Cloud Function 内部将新文件(而不是上传现有文件)写入 Google Cloud Storage 存储桶。

任何想法将不胜感激。

谢谢。

您必须在本地创建文件,然后将其推送到 GCS。 您不能使用 open 在 GCS 中动态创建文件。

为此,您可以在/tmp目录中写入内存文件系统。 顺便说一句,您将永远无法创建大于函数允许的内存量减去代码的内存占用量的文件。 使用 2Gb 的函数,您可以预期最大文件大小约为 1.5Gb。

注意:GCS 不是文件系统,你不必像这样使用它

 from google.cloud import storage
 import io

 # bucket name
 bucket = "my_bucket_name"

 # Get the bucket that the file will be uploaded to.
 storage_client = storage.Client()
 bucket = storage_client.get_bucket(bucket)

 # Create a new blob and upload the file's content.
 my_file = bucket.blob('media/teste_file01.txt')

 # create in memory file
 output = io.StringIO("This is a test \n")

 # upload from string
 my_file.upload_from_string(output.read(), content_type="text/plain")

 output.close()

 # list created files
 blobs = storage_client.list_blobs(bucket)
 for blob in blobs:
     print(blob.name)

# Make the blob publicly viewable.
my_file.make_public()

您现在可以将文件直接写入 Google Cloud Storage。 不再需要在本地创建文件然后上传。

您可以使用 blob.open() 如下:


from google.cloud import storage
    
def write_file():
    client = storage.Client()
        bucket = client.get_bucket('bucket-name')
        blob = bucket.blob('path/to/new-blob-name.txt') 
        ## Use bucket.get_blob('path/to/existing-blob-name.txt') to write to existing blobs
        with blob.open(mode='w') as f:
            for line in object: 
                f.write(line)

您可以在此处找到更多示例和片段: https : //github.com/googleapis/python-storage/tree/main/samples/snippets

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM