I am using Google Cloud Datastore via the python-ndb library (Python 3). My goal is to transactionally create two entities at once. For example, when a user creates an Account
entity, also create a Profile
entity, such that if either entity fails to be created, then neither entity should be created.
From the datastore documentation, it can be implemented like this:
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])
However, there is no example provided by the python-ndb documentation. From chatgpt, I tried something like this:
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
However, I get the error:
TypeError: transactional_wrapper() missing 1 required positional argument: 'wrapped'
You're almost there. It should be
@ndb.transactional()
def _transaction():
Ran your code and got your error. Then amended it to mine and it went through.
Source - https://github.com/googleapis/python-ndb/blob/main/google/cloud/ndb/_transaction.py#L317