在插入数据之前获取 Datastore Key

Getting Datastore Key before inserting data

Cloud Datastore (Entities, Properties, and Keys) 允许使用自动生成的数字 ID(或输入自定义名称)来识别实体。

我想在某些业务逻辑中使用自动生成的数字 ID,然后将实体写入数据存储区

from google.cloud import datastore

ds = datastore.Client('my-project-id')

# Use automatically generated numeric ID.
key = ds.key('MyEntity')

# https://googlecloudplatform.github.io/google-cloud-python/latest/datastore/keys.html
my_id = key.id()

# Some business logic requiring unique ID for MyEntity
data = my_business_logic(my_id)

entity = datastore.Entity(key=key)
entity.update(data)
ds.put(entity)

但是,key.id()None,所以我得到一个 Python TypeError:

TypeError: 'NoneType' object is not callable

Key is documented,所以我可能用错了getter?

默认情况下,实体在 put() 进入数据存储之前不会有完整的密钥(带有数字 ID)。

对于像您这样的情况,您希望在将实体写入数据存储之前了解自动生成的数字 ID,您可以使用数据存储客户端的 allocate_ids 方法,如下所示:

from google.cloud import datastore

ds = datastore.Client('my-project-id')

key = ds.allocate_ids(ds.key('MyEntity'), 1)[0]

my_id = key.id

data = my_business_logic(my_id)

entity = datastore.Entity(key=key)
entity.update(data)
ds.put(entity)

请注意 allocate_ids 有两个参数,incomplete_keynum_ids,所以即使你只想要一个键,你也需要指定它并提取第一个(和仅) 结果列表的成员。