如何从Google App EnginePython 3写入Google Cloud Storage中的文件

问题描述

我需要访问GCS(Google云存储)中的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文件系统为只读文件,并且无法在服务器端创建文件。你可以帮帮我吗?非常感谢!

解决方法

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

,

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

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)
,

您需要使用当前支持Python 2和3的this issue

下面是有关如何上传文件的示例

npm install