在 Tornado 中为用 @run_on_executor 修饰的函数设置超时条件的最佳方法是什么?

What is the best way to set a timeout condition for functions decorated with @run_on_executor in Tornado?

在使用 tornado.concurrent 的 @run_on_executor 装饰器提交给 ThreadPoolExecutor 的 task/function 上设置超时条件的最佳方法是什么?下面的示例 Tornado 处理程序:

import json
import time
import tornado.web
from concurrent.futures import ThreadPoolExecutor
from tornado.concurrent import run_on_executor


class MyHandler(tornado.web.RequestHandler):

    def initialize(self) -> None:
        self.executor = ThreadPoolExecutor(1)

    @run_on_executor
    def blocking_function(self) -> None:
        """ Run Blocking Function on ThreadPoolExecutor. """
        seconds = 10
        time.sleep(seconds)
        response = json.dumps({"message": f"Slept for {seconds} seconds."})
        return response

    async def get(self) -> None:
        response = await self.blocking_function()
        self.write(response)

@run_on_executor 是否存在类似 tornado.gen.with_timeouthere

感谢您的宝贵时间。

由于 run_on_executor returns 一个 Future 对象,你可以将它与 gen.with_timetout:

一起使用
from datetime import timedelta

async def get(self):
    response = await gen.with_timeout(
                   timedelta(seconds=5),
                   self.blocking_function()
               )

    ...

不要忘记处理超时异常。