【问题标题】:Writing a new file to a Google Cloud Storage bucket from a Google Cloud Function (Python)从 Google Cloud Function (Python) 将新文件写入 Google Cloud Storage 存储桶
【发布时间】:2020-05-05 02:01:47
【问题描述】:

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

任何想法都将不胜感激。

谢谢。

【问题讨论】:

    标签: python-3.x google-cloud-platform google-cloud-functions google-cloud-storage


    【解决方案1】:

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

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

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

    【讨论】:

    • 如何将其推送到 GCS?
    • 你在说什么?如果需要,不要犹豫创建一个新问题,共享代码和见解会更容易
    【解决方案2】:
     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()
    

    【讨论】:

    • 或者直接这样做my_file.upload_from_string("This is a test", content_type="text/plain")
    【解决方案3】:

    您现在可以将文件直接写入 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.txt')
        with blob.open(mode='w') as f:
            for line in object: 
                f.write(line)
    

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

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2022-07-25
      • 2019-06-14
      • 2017-11-29
      • 1970-01-01
      • 2019-06-11
      • 2018-06-18
      • 2021-04-25
      • 1970-01-01
      相关资源
      最近更新 更多