gpt4 book ai didi

python - 在 Tornado 中使用数据库操作时如何在自定义装饰器中使用协程

转载 作者:行者123 更新时间:2023-11-28 22:37:03 25 4
gpt4 key购买 nike

我有使用 get 和 post 方法处理请求的处理程序,我想使用我自己的自定义装饰器进行身份验证,而不是 Tornado 本身 @tornado.web.authenticated 装饰器。在我的自定义装饰器中,我需要查询数据库以识别用户,但 Tornado 中的数据库查询与@gen.coroutine 异步。

我的代码是:

处理程序.py;

 @account.utils.authentication
@gen.coroutine
def get(self, page):

account/utils.py:

@tornado.gen.coroutine
def authentication(fun):
def test(self,*args, **kwargs ):
print(self)
db = self.application.settings['db']
result = yield db.user.find()
r = yield result.to_list(None)
print(r)
return test

但是访问时出现错误:

Traceback (most recent call last): File "/Users/moonmoonbird/Documents/kuolie/lib/python2.7/site-packages/tornado/web.py", line 1443, in _execute result = method(*self.path_args, **self.path_kwargs) TypeError: 'Future' object is not callable

谁能遇到过这个,编写自定义装饰器以使用异步数据库操作进行身份验证的正确方法是什么?提前致谢~

最佳答案

装饰器需要同步; 它返回的函数 是协程。您需要更改:

@tornado.gen.coroutine
def authentication(fun):
def test(self, *args, **kwargs):
...
return test

收件人:

def authentication(fun):
@tornado.gen.coroutine # note
def test(self, *args, **kwargs):
...
return test

关于python - 在 Tornado 中使用数据库操作时如何在自定义装饰器中使用协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com