使用 google.cloud.ndb 进行事务操作

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

我通过 python-ndb 库 (Python 3) 使用 Google Cloud Datastore。我的目标是“以事务方式”同时创建两个实体。例如,当用户创建一个 Account 实体时,同时创建一个

Profile
实体,这样如果任一实体创建失败,则不应创建两个实体。

datastore文档

来看,可以这样实现: from google.cloud import datastore client = datastore.Client() def transfer_funds(client, from_key, to_key, amount): with client.transaction(): from_account = client.get(from_key) to_account = client.get(to_key) from_account["balance"] -= amount to_account["balance"] += amount client.put_multi([from_account, to_account])

但是,python-ndb 文档没有提供示例。从chatgpt,我尝试了这样的事情:

from google.cloud import ndb client = ndb.Client() def create_new_account(): with client.context(): @ndb.transactional def _transaction(): account = Account() account.put() profile = Profile(parent=account.key) profile.put() return account, profile try: account, profile = _transaction() except Exception as e: print('Failed to create account with profile') raise e return account, profile

但是,我收到错误:

TypeError: transactional_wrapper() missing 1 required positional argument: 'wrapped'


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

@ndb.transactional() def _transaction():

运行你的代码并得到错误。然后修改成我的就通过了。

来源 -

https://github.com/googleapis/python-ndb/blob/main/google/cloud/ndb/_transaction.py#L317

© www.soinside.com 2019 - 2024. All rights reserved.