只是为此苦苦挣扎。如果我有一个异步请求处理程序,它在执行期间调用其他函数来做某事(例如异步数据库查询),然后它们自己调用“完成”,我是否必须将它们标记为异步?因为如果应用程序的结构类似于示例,我会收到有关多次调用“完成”的错误。我想我错过了什么。
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@gen.engine
def post(self):
#do some stuff even with mongo motor
self.handleRequest(bla)
@gen.engine
def handleRequest(self,bla):
#do things,use motor call other functions
self.finish(result)
是不是所有的函数都要标上async? 谢谢
最佳答案
调用 finish 结束 HTTP 请求见 docs .其他函数不应调用“完成”
我想你想做这样的事情。请注意,有一个额外的参数“回调”被添加到异步函数中:
@tornado.web.asynchronous
@gen.engine
def post(self):
query =''
response = yield tornado.gen.Task(
self.handleRequest,
query=query
)
result = response[0][0]
errors = response[1]['error']
# Do stuff with result
def handleRequest(self, callback, query):
self.motor['my_collection'].find(query, callback=callback)
参见 tornado.gen docs了解更多信息
关于python - 从 Tornado 异步调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17969020/