【问题标题】:GAE python ndb put_async issueGAE python ndb put_async 问题
【发布时间】:2014-04-29 10:42:03
【问题描述】:

我有一个名为 Conversation 的模型,其中一些字段包括 date_createddate_updated 作为 DateTimeProptertyauto_now_addauto_now

如果我使用put() 方法更新模型,date_updated 字段将得到更新。 但是当我使用put_async 方法时,date_updated 字段中的值没有更新。

我也有使用 Python 的 unittest.Testcase 的测试用例,它工作正常。

注意:当我使用 put_async().get_result() 时它可以工作。

示例模型类:

class Conversation(ndb.Model):

   participants = ndb.StringProperty(repeated=True)  
   conversation_name = ndb.StringProperty()
   date_created = ndb.DateTimeProperty(required=True, auto_now_add=True)
   date_updated = ndb.DateTimeProperty(required=True, auto_now=True)

   @staticmethod
   def update_conversation_date_by_id(conversation_id):
       conversation = Conversation.get_by_id(conversation_id) if conversation_id else None
       if conversation is None:
           raise CannotFindEntity("Given conversation_id is not found")
       else:
           conversation.put_async().get
       return conversation

【问题讨论】:

标签: google-app-engine python-2.7 google-cloud-datastore


【解决方案1】:

如果请求处理程序在 NDB put 完成之前退出,则 put 可能永远不会发生。

class MyRequestHandler(webapp2.RequestHandler):
  def get(self):
    acct = Account.get_by_id(users.get_current_user().user_id())
    acct.view_counter += 1
    future = acct.put_async()
    # ...read something else from Datastore...
    template.render(...)
    future.get_result()

尝试在该代码块中添加类似于最后一行的内容以强制其等待。

在这个例子中,调用 future.get_result 有点傻: 应用程序从不使用 NDB 的结果。代码就在里面 确保请求处理程序在 NDB put 之前不会退出 完成;如果请求处理程序退出得太早,put 可能永远不会 发生。为方便起见,您可以使用 @ndb.toplevel。这告诉处理程序不要退出,直到它 异步请求已完成。这反过来又可以让您发送 请求而不担心结果。

https://developers.google.com/appengine/docs/python/ndb/async

【讨论】:

    【解决方案2】:

    当主线程停止时异步方法停止执行(请求处理程序完成)......所以很可能你的代码没有执行。 这可以通过将 @ndb.toplevel 添加到您的请求处理程序来防止。然后处理程序将等待您的异步完成。

    https://developers.google.com/appengine/docs/python/ndb/async

    当请求处理程序完成时,异步不允许您运行代码。 async 允许您在同一请求处理程序线程上等待异步命令时运行其他(异步)命令:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多