Google App Engine 启动时自动填充 google 数据存储中的初始数据

Google App Engine on startup autofill initial data in google data store

我有一个 Google App Engine Python 应用程序。我正在使用 google 数据存储作为服务器动态内容的数据库。我想在启动 google 应用引擎应用程序时自动填充 google 数据存储区中的一些数据。

启动我正在使用的应用程序

dev_appserver.py app.yaml

我有一个 python 脚本来自动填充初始数据,但不知道如何在启动应用程序时将该脚本配置为 运行 一次。

此外,我已经使用带有 jinja2 模板的 webapp2 构建了网站。

要在开发环境中进行这项工作,最简单的做法是 运行 在您的 appengine_config.py 文件中编写代码(如果您没有这样的文件,请在应用程序的顶层,与 app.yaml).

在同一文件夹中
# Make this the last item in app.yaml - set up vendoring etc first.

from models import FooModel

# Delete existing records
keys = FooModel.query().fetch(keys_only=True)
ndb.delete_multi(keys)

data = get_data_from_somewhere()

# Assumes data is an iterable of dicts
entities = [FooModel(**item) for item in data]
ndb.put_multi(entities)

了解此方法在云中无法可靠地工作。这是因为在云中可能有多个应用程序实例一直在启动和停止。最好设计您的应用程序,以便不需要在实例启动时(甚至在每次部署后)重新初始化数据存储。