Noah McIlraith Noah McIlraith - 4 months ago 49
Python Question

Providing arguments to transactions in Datastore Plus (NDB)

I'm having trouble working out how to pass in arguments into transactions when using Datastore Plus.

Could someone please rewrite this regular-datastore example code?

from google.appengine.ext import db

class Accumulator(db.Model):
counter = db.IntegerProperty()

def increment_counter(key, amount):
obj = db.get(key)
obj.counter += amount

q = db.GqlQuery("SELECT * FROM Accumulator")
acc = q.get()

db.run_in_transaction(increment_counter, acc.key(), 5)

I'm particularly interested in the datastore plus equivalent of that last line.

The datastore plus documentation's example code doesn't deal with arguments at all (hardcoded inside the transaction).


Assuming you can follow the example from the docs, the answer is to use a lambda (or a named helper function). E.g.

yield context.transaction(lambda: increment_counter(acc.key(), 5))