python - Get current user Async in Tornado -
when use get_current_user() need check few things in redis (use tornado-redis) asynchronously.
i doing 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 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, want use authenticated_async decorator:
class indexpagehandler(baseclass, requesthandler): @authenticated_async def get(self): self.render("index.html")
but have in console 123.
whats wrong? how fix that?
thanks!
update
i have updated code yield result
.
in auth_cookie have cfae7a25-2b8b-46a6-b5c4-0083a114c40e
.
then go 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 returns 1 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 have:
cookie b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e' 123 user_async b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e' current user none
get_secure_cookie()
returns byte string; since cookie printed out b'
prefix must on python 3. on python 3, tornado-redis
appears expect unicode strings instead of byte strings; input not unicode string converted 1 str()
function. adds b'
prefix seen above, querying b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
, not cfae7a25-2b8b-46a6-b5c4-0083a114c40e
the solution convert cookie str
before sending redis: auth_cookie = tornado.escape.native_str(auth_cookie)
Comments
Post a Comment