Cloud NDB:以事务方式放置()多个实体

问题描述 投票:0回答:1

[在某些情况下,我们必须一次保存两个或多个数据存储实体(两个实体都被保存,或者两个都不保存)。对于我的示例,我想在创建用户实体时创建一个UserProfile实体。

从实体导入用户,UserProfile

def create_user_and_profile():
    # First, create the User entity
    user = User(email=email, password=password_hash)
    user.put()

    # Then, create a UserProfile entity
    # that takes a user.key as parent
    user_profile = UserProfile(parent=user.key)
    user_profile.put()

上面的函数不是原子的。可能只有一个或两个实体没有成功保存。

如何使这个原子化?

python google-app-engine google-cloud-platform app-engine-ndb
1个回答
0
投票

您可以使用transactional中的ndb装饰器。如果有任何记录无法保存,则将不会有任何记录:

from google.cloud import ndb


@ndb.transactional()
def create_user_and_profile():
    # First, create the User entity
    user = User(email=email, password=password_hash)
    user.put()

    # Then, create a UserProfile entity
    # that takes a user.key as parent
    user_profile = UserProfile(parent=user.key)
    user_profile.put()

with ndb_client.context(): # ndb client instance
    create_user_and_profile()
© www.soinside.com 2019 - 2024. All rights reserved.