【问题标题】:How to write to a file in Google Cloud Storage from Google App Engine (Python 3)如何从 Google App Engine(Python 3)写入 Google Cloud Storage 中的文件
【发布时间】:2020-12-01 02:47:36
【问题描述】:

我需要访问 GCS(Google Cloud Storage)中的 json 文件并从 Google App Engine(PY3 标准运行时)更改其内容。虽然我可以通过以下方式在 GCS 中读取文件的内容:

from google.cloud import storage
storage_client = storage.Client()
bucket = storage_client.bucket('bucket_name')
blob = bucket.blob('file_name')
file_content = blob.download_as_string().decode('utf-8')

我不知道如何直接写入 GCS 文件。如果我可以删除 GCS 文件并重新上传在某个临时文件夹中创建的文件也可以,但看起来 GAE 文件系统是只读的,我无法在服务器端创建文件。你可以帮帮我吗?非常感谢!

【问题讨论】:

    标签: google-app-engine google-cloud-platform google-cloud-storage google-app-engine-python


    【解决方案1】:

    我终于使用了 Blod.upload_from_string() 来避免创建临时文件。

    【讨论】:

      【解决方案2】:

      您需要使用当前支持 Python 2 和 3 的Client Library

      如何上传文件的示例如下

      from gcloud import storage
      from oauth2client.service_account import ServiceAccountCredentials
      import os
      
      
      credentials_dict = {
          'type': 'service_account',
          'client_id': os.environ['BACKUP_CLIENT_ID'],
          'client_email': os.environ['BACKUP_CLIENT_EMAIL'],
          'private_key_id': os.environ['BACKUP_PRIVATE_KEY_ID'],
          'private_key': os.environ['BACKUP_PRIVATE_KEY'],
      }
      credentials = ServiceAccountCredentials.from_json_keyfile_dict(
          credentials_dict
      )
      client = storage.Client(credentials=credentials, project='myproject')
      bucket = client.get_bucket('mybucket')
      blob = bucket.blob('myfile')
      blob.upload_from_filename('myfile')
      

      【讨论】:

        【解决方案3】:

        您可以使用以下代码上传文件

        from google.cloud.storage import Blob
        
        client = storage.Client(project="my-project")
        bucket = client.get_bucket("my-bucket")
        blob = Blob("secure-data", bucket)
        with open("my-file", "rb") as my_file:
            blob.upload_from_file(my_file)
        

        【讨论】:

          猜你喜欢
          • 2012-01-02
          • 2018-07-22
          • 1970-01-01
          • 2015-07-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-08
          • 2021-11-05
          相关资源
          最近更新 更多