【问题标题】:how to return value from tornado.ioloop.IOLoop instance add_future method如何从 tornado.ioloop.IOLoop 实例 add_future 方法返回值
【发布时间】:2016-08-30 15:34:29
【问题描述】:

我正在使用 RethinkDBTornado 和异步方法。基于我在RethinkDB 中的数据模型,在为我的topic 表插入一条记录后,我还必须在user_to_topic 表中更新/插入新记录。这是我的发布请求处理程序的基本设置。

class TopicHandler(tornado.web.RequestHandler):
  def get(self):
     pass

  @gen.coroutine
  def post(self, *args, **kwargs):
      # to establish databse connection
      connection = rth.connect(host='localhost', port=00000, db=DATABASE_NAME)
      # Thread the connection
      threaded_conn = yield connection

      title = self.get_body_argument('topic_title')
      # insert into table
      new_topic_record = rth.table('Topic').insert({
         'title': topic_title,
     }, conflict="error",
         durability="hard").run(threaded_conn)

     # {TODO} for now assume the result is always written successfully
     io_loop = ioloop.IOLoop.instance()
     # I want to return my generated_keys here 
     io_loop.add_future(new_topic_record, self.return_written_record_id)
     # do stuff with the generated_keys here, how do I get those keys

  def return_written_record_id(self, f):
     _result = f.result()
     return _result['generated_keys']

插入操作完成后,Future 对象通过Future.result() 方法从RethinkDB 插入操作返回结果,我可以使用结果的generated_keys 属性检索新记录的ID。根据Tornadodocument,我可以在我的回调函数return_written_record_id 中处理结果。当然,我可以在 return_written_record_id 函数中执行所有其他数据库操作,但是是否可以将所有 id 返回到我的 post 函数?或者这就是它必须在 tornado 中使用协程的方式?

任何建议将不胜感激。谢谢!

【问题讨论】:

    标签: python tornado rethinkdb coroutine


    【解决方案1】:

    简单地做:

    result = yield new_topic_record
    

    每当您在协程中产生 Future 时,Tornado 都会暂停协程,直到 Future 被解析为一个值或异常。然后 Tornado 通过传入值或在“yield”表达式处引发异常来恢复协程。

    有关详细信息,请参阅Refactoring Tornado Coroutines

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 2012-07-14
      • 2013-05-11
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      相关资源
      最近更新 更多