【问题标题】:Cloud NDB: transactionally put() multiple entitiesCloud NDB:事务性 put() 多个实体
【发布时间】:2020-07-13 20:14:27
【问题描述】:

在某些情况下,我们必须一次保存两个或多个数据存储实体(两个实体都保存或都不保存)。对于我的示例,我想在创建 User 实体时创建一个 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】:

    ndb 中有 transactional 装饰器可以使用。如果任何记录无法保存,它们都不会:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2013-01-27
      • 1970-01-01
      • 2016-09-09
      • 2011-03-29
      相关资源
      最近更新 更多