2

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

我的代码是:

处理程序.py;

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

账号/utils.py:</p>

@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

但是访问时出现错误:</p>

Traceback(最近一次调用最后一次):文件“/Users/moonmoonbird/Documents/kuolie/lib/python2.7/site-packages/tornado/web.py”,第 1443 行,在 _execute result = method(*self.path_args, **self.path_kwargs) TypeError: 'Future' object is not callable

任何人都可以在此之前遇到这个问题,编写自定义装饰器以使用异步数据库操作进行身份验证的正确方法是什么?先谢谢了~

4

1 回答 1

4

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

@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
于 2016-04-30T07:13:31.820 回答