最诚挚的问候,
答案 0 :(得分:1)
这在某种程度上取决于您希望应用程序如何工作,但是您可以使用Python Client for Google Cloud Datastore(在Python3.X中可以使用)来完成类似的工作。
例如,您可以通过执行以下操作来使用此库更新现有实体:
from flask import Flask
from google.cloud import datastore
app = Flask(__name__)
@app.route('/')
def mainhandler():
client = datastore.Client()
# Entity to update Kind and ID. Replace this values
# with ones that you know that exist.
entity_kind = 'Foo-entity'
entity_id = 123456789
key = client.key(entity_kind, entity_id)
entity = client.get(key)
entity.update({
"foo": u"bar",
"year": 2019
})
client.put(entity)
return "Entity updated"
如您所见,要更新现有实体,您将需要其种类和唯一ID(没有其他方法)。
但是,创建实体时不需要这样做,只要创建后就可以在运行时对其进行更新:
from flask import Flask
from google.cloud import datastore
app = Flask(__name__)
@app.route('/')
def mainhandler():
client = datastore.Client()
entity_kind = 'Ticket-sale'
key = client.key(entity_kind)
''' It is better to let Datastore create the Key
(unless you have some method to crate unique ID's),
so we call the allocate_ids method, and only keep the Key object'''
key = client.allocate_ids(key, 1)[0]
entity = datastore.Entity(key=key)
entity.update({
"foo": u"bar",
"year": 20192
})
client.put(entity) # This creates the entity
# update the entity once more with another property
entity.update({
"month": u"January",
})
client.put(entity)
return "Entity created"
请注意,您必须使用u"string"
字面量,以提醒数据存储区您要传递的字符串是用unicode编码的,否则访问时,它将显示为由随机字符组成的字符串属性值。
同样,不要忘记通过添加行requirements.txt
来更新google-cloud-datastore
文件以导入该库。