When I use get_current_user() I need to check few things in Redis (use tornado-redis) asynchronously.
I am doing the following:
def authenticated_async(method):
@gen.coroutine
def wrapper(self, *args, **kwargs):
self._auto_finish = False
self.current_user = yield gen.Task(self.get_current_user_async)
if not self.current_user:
self.redirect(self.reverse_url('login'))
else:
result = method(self, *args, **kwargs) # updates
if result is not None:
yield result
return wrapper
class BaseClass():
@gen.coroutine
def get_current_user_async(self,):
auth_cookie = self.get_secure_cookie('user') # cfae7a25-2b8b-46a6-b5c4-0083a114c40e
user_id = yield gen.Task(c.hget, 'auths', auth_cookie) # 16
print(123, user_id)
return auth_cookie if auth_cookie else None
For example, I want to use authenticated_async decorator:
class IndexPageHandler(BaseClass, RequestHandler):
@authenticated_async
def get(self):
self.render("index.html")
But I have in console only 123.
Whats wrong? How to fix that?
Thanks!
UPDATE
I have updated the code with yield result
.
In auth_cookie I have cfae7a25-2b8b-46a6-b5c4-0083a114c40e
.
Then I go to terminal:
127.0.0.1:6379> hget auths cfae7a25-2b8b-46a6-b5c4-0083a114c40e
"16"
So,
user_id = yield gen.Task(c.hget, 'auths', auth_cookie)
print(123, user_id)
Must return
123 16
But it returns one 123
UPDATE 1
With
class IndexPageHandler(BaseClass, RequestHandler):
@gen.coroutine
def get(self):
print('cookie', self.get_secure_cookie('user'))
user_async = yield self.get_current_user_async()
print('user_async', user_async)
print('current user', self.current_user)
self.render("index.html",)
In console I have:
cookie b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
123
user_async b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
current user None
get_secure_cookie()
returns a byte string; since the cookie printed out with ab'
prefix you must be on Python 3. On Python 3,tornado-redis
appears to expect unicode strings instead of byte strings; any input that is not a unicode string will be converted to one with thestr()
function. This adds theb'
prefix seen above, so you are querying forb'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
, notcfae7a25-2b8b-46a6-b5c4-0083a114c40e
The solution is to convert the cookie to a
str
before sending it to redis:auth_cookie = tornado.escape.native_str(auth_cookie)