Tornado Asynchronous Handler

前端 未结 3 892
半阙折子戏
半阙折子戏 2020-12-09 21:10

I am attempting to implement get_current_user in the RequestHandler for Tornado, but I need the call to block while waiting on the asynchronous call to my database. Decorat

3条回答
  •  余生分开走
    2020-12-09 21:56

    How about having get_current_user return a Future that you signal when the asynchronous response from your database is returned?

    class BaseHandler(tornado.web.RequestHandler):
        def get_current_user(self):
            future = Future()
            def query_cb(user):
                future.set_result(user or None)
            database.get(username='test', password='t3st', callback=query_cb)
            return future
    
    
    class MainHandler(BaseHandler):
        @gen.coroutine
        def get(self):
            user = yield self.get_current_user()
            self.write('user: ' + user)
            # ... actual request processing
    

提交回复
热议问题