python - 从 Tornado 异步调用函数

标签 python asynchronous tornado yield

只是为此苦苦挣扎。如果我有一个异步请求处理程序,它在执行期间调用其他函数来做某事(例如异步数据库查询),然后它们自己调用“完成”,我是否必须将它们标记为异步?因为如果应用程序的结构类似于示例,我会收到有关多次调用“完成”的错误。我想我错过了什么。

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/

相关文章:

python - 抽象基类 : raise NotImplementedError() in `__init__.py` ?

python - 按 col Y 分组时在 pandas DataFrame 的 col X 中查找最小值

javascript - 如何同步(以编程方式)运行 Grunt 任务?

windows - 套接字异步操作是否会同步完成?

python - 我想为 python 制作/拥有像 'future' async API 这样的 scala

python - AsyncHTTPClient 阻止我的 Tornado IOLoop

python - 将 Qt Pyside2 与 asyncio await 语法一起使用?

python - 从两个类别列 pandas 创建一个类别列

django - 如何在Django + Pusher中存储聊天记录?需要 Tornado 或 celery 吗?

python - 如何在其他函数中移动数据库请求(使用产量)?