Tornado Asynchronous Handler

血红的双手。 提交于 2019-11-28 09:24:06

Do a blocking database operation instead of the non blocking described above (There is a blocking mysql lib shipped with tornado).

From the Tornado wiki page about threads and concurrency: "Do it synchronously and block the IOLoop. This is most appropriate for things like memcache and database queries that are under your control and should always be fast. If it's not fast, make it fast by adding the appropriate indexes to the database, etc."

https://github.com/facebook/tornado/wiki/Threading-and-concurrency

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

I thought Tornado allowed you to make either blocking or non-blocking requests.

Here is Tornado being used for both: https://bitbucket.org/nephics/tornado-couchdb/src/147579581b47/couch.py

Disclaimer: I know very little of Python and Tornado.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!