【发布时间】:2016-08-30 15:34:29
【问题描述】:
我正在使用 RethinkDB 和 Tornado 和异步方法。基于我在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