当我使用get_current_user()时,我需要异步检查Redis中的一些东西(使用tornado-redis).
我正在做以下事情:
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
Run Code Online (Sandbox Code Playgroud)
例如,我想使用authenticated_async装饰器:
class IndexPageHandler(BaseClass, RequestHandler):
@authenticated_async
def get(self):
self.render("index.html")
Run Code Online (Sandbox Code Playgroud)
但我在控制台只有123.
怎么了?如何解决?
谢谢!
UPDATE
我已经更新了代码yield result.
在auth_cookie我有cfae7a25-2b8b-46a6-b5c4-0083a114c40e.
然后我去终点站:
127.0.0.1:6379> hget auths cfae7a25-2b8b-46a6-b5c4-0083a114c40e
"16"
Run Code Online (Sandbox Code Playgroud)
所以,
user_id = yield gen.Task(c.hget, 'auths', auth_cookie)
print(123, user_id)
Run Code Online (Sandbox Code Playgroud)
必须回来
123 16
Run Code Online (Sandbox Code Playgroud)
但它返回一个123
更新1
同
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",)
Run Code Online (Sandbox Code Playgroud)
在控制台我有:
cookie b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
123
user_async b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
current user None
Run Code Online (Sandbox Code Playgroud)
get_secure_cookie()返回一个字节字符串;因为打印出的 cookie 带有b'前缀,所以您必须使用 Python 3。在 Python 3 上,tornado-redis似乎需要 unicode 字符串而不是字节字符串;任何非 unicode 字符串的输入都将通过该str()函数转换为字符串。这会添加b'上面看到的前缀,因此您正在查询b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e',而不是cfae7a25-2b8b-46a6-b5c4-0083a114c40e
解决方案是在将cookiestr发送到redis之前将其转换为a:auth_cookie = tornado.escape.native_str(auth_cookie)
| 归档时间: |
|
| 查看次数: |
984 次 |
| 最近记录: |