【问题标题】:ndb.transaction_async() vs async calls inside a transactionndb.transaction_async() 与事务中的异步调用
【发布时间】:2013-01-27 07:11:39
【问题描述】:

我正在将我的 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 是可以选择的,但我宁愿依靠专家意见/建议...

【问题讨论】:

    标签: google-app-engine app-engine-ndb


    【解决方案1】:

    是的,#3 绝对是要走的路。另外两个的问题是它们混合了异步和同步代码,除了在应用程序的最顶层之外,这通常不是一件好事。

    PS。事实上,如果它是一个 tasklet,事务会等待回调。

    【讨论】:

    • 我知道这是一个旧答案,但从我在源代码中看到的情况来看,ndb/model.py 中的所有事务/事务函数最终都以 Context 类的事务方法结束。 ..它本身被标记为@tasklet。看起来事务中的任何代码都需要是异步的,否则它将混合同步/异步代码,是吗? github.com/GoogleCloudPlatform/datastore-ndb-python/blob/master/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2015-03-01
    • 2023-03-11
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多