我正在将我的 ndb 代码库尽可能多地移动到异步的过程中。有一种情况我不太确定如何进行:事务。
正如我所看到的,我有 3 个可用选项:
选项 1:ndb.transaction()同步调用,并让事务的函数调用异步方法。
def option_1():
    @ndb.tasklet
    def txn():
        e = yield Foo.get_by_id_async(some_id)
        if e is None:
            e = yield Foo().put_async()
        raise ndb.Return(e)
    # The doc for ndb.transaction() says that it takes a function or tasklet.
    # If it's a tasklet, does it wait on the Future that is returned?
    # If it doesn't wait, what is the proper way to call a tasklet in a transaction
    # and get access to its return value?
    return ndb.transaction(txn)
选项 2:ndb.transaction()异步调用,并让事务的函数调用同步方法。
@ndb.toplevel
def option_2():
    def txn():
        e = Foo.get_by_id(some_id)
        if e is None:
            e = Foo().put()
        return e
    result = yield ndb.transaction_async(txn)
    return result
选项 3:ndb.transaction()异步调用,并让事务的函数调用异步方法。
@ndb.toplevel
def option_3():
    @ndb.tasklet
    def txn():
        e = yield Foo.get_by_id_async(some_id)
        if e is None:
            e = yield Foo().put_async()
        raise ndb.Return(e)
    result = yield ndb.transaction_async(txn)
    return result
我觉得选项 3 是可以选择的,但我宁愿依靠专家意见/建议......