在Tornad中获取当前用户异步

2024-06-02 08:57:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用获取当前用户()时,我需要异步检查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

例如,我想使用authenticated_asyncdecorator:

^{pr2}$

但我在控制台里只有123个。在

怎么了?怎么解决?在

谢谢!在

更新

我已经用yield result更新了代码。在

认证cookie中,我有cfae7a25-2b8b-46a6-b5c4-0083a114c40e。在

然后我去终点站:

127.0.0.1:6379> hget auths cfae7a25-2b8b-46a6-b5c4-0083a114c40e
"16"

所以

user_id = yield gen.Task(c.hget, 'auths', auth_cookie)
print(123, user_id)

必须返回

123 16

但它返回一个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",)

在控制台中,我有:

cookie b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
123 
user_async b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e'
current user None

Tags: selfauthidgetasynccookiedefresult
3条回答

查看的doc字符串一般任务公司名称:

Takes a function (and optional additional arguments) and runs it with those arguments plus a callback keyword argument.

c.hget是否接受回调参数?否则,回调将抛出一个异常,未来不会设置结果,因此print语句不打印用户id

答案就在你的包装合作计划中了。在

        if result is not None:
            yield result

你不想产生结果,而是想从协同程序中“返回”。但是,由于Python不允许使用来自生成器的非空返回,因此需要将其作为龙卷风可以展开的包装异常引发,并将结果传递给调用方(get_current_user

^{pr2}$

这样做了,你应该会发现它是有效的。在

get_secure_cookie()返回一个字节字符串;由于cookie是用b'前缀打印出来的,所以必须使用python3。在python3上,tornado-redis似乎希望使用unicode字符串,而不是字节字符串;任何不是unicode字符串的输入都将转换为使用str()函数的输入。这将添加上面看到的b'前缀,因此您查询的是b'cfae7a25-2b8b-46a6-b5c4-0083a114c40e',而不是{}

解决方案是先将cookie转换为str,然后再将其发送到redis:auth_cookie = tornado.escape.native_str(auth_cookie)

相关问题 更多 >