我通过 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'