「@ndb.toplevel」タグアーカイブ

PythonのNDB Asynchronous(非同期)での@ndb.toplevelの使い方

Google App EngineでNDB Asynchronousを使うときに@ndb.toplevelというのが出てきた。

class MyRequestHandler(webapp2.RequestHandler):
@ndb.toplevel
def get(self):
acct = Account.get_by_id(users.get_current_user().user_id())
acct.view_counter += 1
acct.put_async() # Ignoring the Future this returns
# …read something else from Datastore…
template.render(…)

マニュアルのサンプルコードがこれで、最初は何のことかチンプンカンプンだった。
一晩寝て次の日になってやっとわかってきて
async()は、複数のことを同時にできるから、例えば、100個の命令を同時に出して、まだ全部の命令が完了していないのに
次の命令、サンプルだとtemplate.render(…)が実行されてしまうと、async()のまだ終わってないのに、次の段階に進んでしまい永遠に
async()の内容が完了しないままになることがあるかもしれない。そこで登場するのが@ndb.toplevelで、これをつけると、async()が完了するまで待ってくれる、ということらしい。

1