2016-05-05 7 views
0

RethinkDBTornadoを非同期で使用しています。 RethinkDBのデータモデルをベースに、topicテーブルのレコードを挿入すると、新しいレコードをuser_to_topicテーブルに更新/挿入する必要があります。ここに私のポストリクエストハンドラの基本的なセットアップがあります。挿入操作が終了した後tornado.ioloop.IOLoopインスタンスadd_futureメソッドから値を返す方法

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'] 

、私は結果のgenerated_keys属性を使用して、新しいレコードのIDを取得することができFuture.result()法によるRethinkDB挿入操作からの戻り結果にFutureオブジェクト。 Tornadodocumentによると、私はコールバック関数return_written_record_idの結果を持つことができます。もちろん、return_written_record_id関数内の他のすべてのデータベース操作を行うことはできますが、すべてのIDを関数postに返すことは可能ですか?それとも、トルネードでコルーチンを使用しなければならないのですか?

ご意見をお寄せください。ありがとうございました!

答えて

1

は単純に実行します。今後は、値または例外に解決されるまで、あなたはコルーチンの内側の未来をもたらすたび

result = yield new_topic_record 

は、トルネードはコルーチンを一時停止します。その後、Tornadoは値を渡すか、 "yield"式で例外を発生させることによってコルーチンを再開します。

詳細については、Refactoring Tornado Coroutinesを参照してください。

関連する問題