我遇到了Tornado中异步函数的模糊情况。
我一直在研究的系统只接收POST请求并异步提供它们。但现在我必须为服务IE8用户添加GET请求处理。 问题是GET请求功能完全与post请求相同。
我不想简单地复制粘贴我的代码,所以我来到了以下解决方案:
class ExampleHandler(BaseHandler):
def _request_action(self):
""" Function that incapsulates all actions, that should be performed in request
"""
yield self.motor.col1.insert({"ex1": 1})
raise Return
@gen.coroutine
def get(self):
""" GET request handler - need for IE8- users. Used ONLY for them
"""
self._request_action()
@gen.coroutine
def post(self):
""" POST handling for all users, except IE8-
"""
self._request_action()
我对异步装饰器有很多疑问。是否足以在装饰器中包装GET / POST处理程序,并将应该执行的所有操作放在同步工作函数中?或者我也应该把它包起来?
答案 0 :(得分:2)
如果您yield
在函数内部Future
,则必须使用@gen.coroutine
对其进行换行。
所以,用_request_action
@gen.coroutine
@gen.coroutine
def _request_action(self):
""" Function that incapsulates all actions, that should be performed in request
"""
result = yield self.motor.col1.insert({"ex1": 1})
raise gen.Return(result) # that is how you can return result from coroutine
此外,所有协同程序必须由yield
调用:
@gen.coroutine
def get(self):
""" GET request handler - need for IE8- users. Used ONLY for them
"""
result = yield self._request_action()
# do something with result, if you need
@gen.coroutine
def post(self):
""" POST handling for all users, except IE8-
"""
result = yield self._request_action()
# do something with result, if you need