Python 在tornado中处理db操作时如何在custom decorator中使用协同程序

Python 在tornado中处理db操作时如何在custom decorator中使用协同程序,python,tornado,tornado-motor,Python,Tornado,Tornado Motor,我有使用get和post方法处理请求的处理程序,我希望使用我自己的自定义装饰器进行身份验证,而不是使用tornado本身@tornado.web.authenticated装饰器。在我的自定义decorator中,我需要查询db以识别用户,但是tornado中的db查询与@gen.coroutine是异步的 我的代码是: 1.py @account.utils.authentication @gen.coroutine def get(self, page): 帐户/util

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

我的代码是:

1.py

 @account.utils.authentication
    @gen.coroutine
    def get(self, page):
帐户/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
但当访问它时出现错误:

回溯(最近一次调用上次):文件 “/Users/moonbird/Documents/kuolie/lib/python2.7/site packages/tornado/web.py”, 第1443行,in_执行 结果=方法(*self.path_args,**self.path_kwargs)类型错误:“Future”对象不可调用


如果以前有人遇到过这个问题,那么编写自定义decorator以使用异步db操作进行身份验证的正确方法是什么?提前感谢~

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

@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