David - Musings of an SRE

How to set current_user in Tornado asynchronously

Something that I’ve missed when working on setting the current_user upon @tornado.web.authenticated.

Normally, you’d set get_current_user(self) in the RequestHandler which is used by @tornado.web.authenticated to pull/query the current_user that is logged on.

It is fine until you start to utilize asynchronous functions within the get_current_user(self).

Quick notes:

  • get_current_user(self) cannot be a coroutine. So no @tornado.gen.coroutine decorator before it. This also means that it cannot perform yield functions from elsewhere.
  • when required to use a async function to pull user information, use prepare(self) instead.

This will look something like:

@gen.coroutine
def prepare(self):
    user_id_cookie = self.get_secure_cookie("user_id")
    if user_id_cookie:
        self.current_user = yield load_user(user_id_cookie)

References