如何在 Python/Tornado 中使用方法 run_in_executor 调用异步函数?

How do I call an async function with method run_in_executor in Python/Tornado?

我有一个 python 文件,其中有一个龙卷风请求处理程序 class,其中包含以下相关代码:

executor = concurrent.futures.ThreadPoolExecutor(max_workers = 20)
from tornado.platform.asyncio import AnyThreadEventLoopPolicy
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())

class MainHandler(tornado.web.RequestHandler):
   async def connect(self):
      # some code
      loop = asyncio.get_event_loop()
      await loop.run_in_executor(executor, self.connect_function)

   async def connect_function(self):
      #some code with an await operation somewhere here

所以我的主要目标是能够将请求处理程序与线程一起使用。我发现我可以做到这一点的方法是使用方法 run_in_executor。这里的问题是,在 connect 方法中,我想等待也是异步的 connect_function 的结束,这通常会引发错误: RuntimeWarning: coroutine 'MainHandler.connect_function' was never awaited 。 我的问题是这是否是我可以让线程在这个龙卷风请求处理程序中工作的唯一方法,如果是这样,如果有办法我可以等待使用方法 run_in_executor.[=18= 执行异步函数]

我认为异步处理在版本 6 中发生了变化。

所以一些例子/howtos 可能会产生误导。您可能想查看 tornado 文档页面以获取最新示例。点赞 here 向下滚动查看异步代码示例

您不能 运行 ThreadPoolExecutor 中的异步函数(除非您还 运行 另一个事件循环,这通常不是您想要的)。您可以在主事件循环上安排回调,然后在线程上等待它,但这很复杂。作为一般规则,当你使用像 Tornado 这样的异步框架时,你希望尽可能多地停留在事件循环线程上,并且只在必要时将事情发送到 ThreadPoolExecutor(然后让这些函数 return 到主线程,而不是尝试从线程回调异步代码)。