使用在 GAE 上运行的 python 写入文本文件

Writing to text file with python running on GAE

我需要让我的 python 应用商店在我已经在 GAE 上的 GCS 存储桶上创建的文件中存储一些文本。

到目前为止,我找到的所有文档都涵盖了比我的简单用例更复杂的示例,我越来越迷失方向了。

我真正想做的就是在 GCS 上找到以下内容的等效项(包括在 GCS 上复制此内容所需的任何可能的导入):

with open("../somedir/somefile.txt", "a") as myfile:
    myfile.write("appended text")

有什么建议吗?

您不能在 GCS 中修改文件。一旦他们关闭就是这样。为了追加,我会这样做:

import cloudstorage
from google.appengine.api import app_identity


bucketName = app_identity.get_default_gcs_bucket_name()

class MainPage(webapp2.RequestHandler):

    def get(self):

        fileName = "/" + bucketName + "/somedir/somefile.txt"

        try:
            with cloudstorage.open(fileName, "r") as gcsFile:
                tempStorage = gcsFile.read()
                tempStorage += "\n"
        except:
            tempStorage = ""

        with cloudstorage.open(fileName, "w") as gcsFile:
            gcsFile.write(tempStorage + "appended text")

        with cloudstorage.open(fileName, "r") as gcsFile:
            output=  gcsFile.read()  
        self.response.out.write(output)

正在写:

import cloudstorage
from google.appengine.api import app_identity

bucketName = app_identity.get_default_gcs_bucket_name()
fileName = "/" + bucketName + "/somedir/somefile.txt"

with cloudstorage.open(fileName, "w") as gcsFile:
            gcsFile.write("text")

我建议在 GAE 上将数据写入或附加到 /tmp/file。 如果文件做好了,不需要再修改了,可以上传文件到GCS,这样效率会更高。