[英]how to use coroutine in custom decorator when working with db operations in tornado
I have handlers that handle request with get and post method,i want to use authentication with my own custom decorator,not tornado itself @tornado.web.authenticated decorator. 我有使用get和post方法处理请求的处理程序,我想与我自己的自定义装饰器一起使用身份验证,而不是龙卷风本身@ tornado.web.authenticated装饰器。 In my custom decorator,i need to query the db to identify the user,but db query in tornado are asynchronously with @gen.coroutine.
在我的自定义装饰器中,我需要查询数据库以标识用户,但是龙卷风中的数据库查询与@ gen.coroutine异步。
My codes are: 我的代码是:
handlers.py; handlers.py;
@account.utils.authentication
@gen.coroutine
def get(self, page):
account/utils.py: 帐户/ 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
but the erros occurred when accessed it : 但是访问时发生了错误:
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
追溯(最近一次通话):文件“ /Users/moonmoonbird/Documents/kuolie/lib/python2.7/site-packages/tornado/web.py”,行1443,_execute result = method(* self.path_args, ** self.path_kwargs)TypeError:“ Future”对象不可调用
can anyone meet this before,what is the correctly way to write custom decorator to authenticate with async db operation ? 谁能满足这个要求,用异步db操作编写自定义装饰器进行身份验证的正确方法是什么? thanks in advance~
提前谢谢〜
The decorator needs to be synchronous; 装饰器需要同步; it's the function it returns that's a coroutine.
它是返回的函数 ,是协程。 You need to change:
您需要更改:
@tornado.gen.coroutine
def authentication(fun):
def test(self, *args, **kwargs):
...
return test
To: 至:
def authentication(fun):
@tornado.gen.coroutine # note
def test(self, *args, **kwargs):
...
return test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.