Using async in spawn_callback to write causes RuntimeError: Cannot write() after finish()

Using async in spawn_callback to write causes RuntimeError: Cannot write() after finish()

我正在尝试让后台进程每 10 秒运行一次,以将一些随机内容写入网页。页面加载会触发一次这个后台进程。 async def do_something() 适用于 print(message) 但在 self.write(message)

上失败

我不确定我是否应该将 @tornado.gen.coroutine 装饰器添加到 do_something 但我试过了并得到了引用说它从未被等待过。

"""
Python 3.5
This is the MainHandler being called from the def main()
"""
class MainHandler(tornado.web.RequestHandler):

    def get(self):
        global background_flag

        self.write("Hello, world")
        # Coroutines that loop forever are generally started with spawn_callback()
        if not background_flag:
            print ("Launching spawn_callback ...")
            tornado.ioloop.IOLoop.current().spawn_callback(self.minute_loop)
            background_flag = True

    async def minute_loop(self):
        while True:
            # await self.do_something() #do_something must be an async def as well non-blocking
            await self.do_something()
            await tornado.gen.sleep(10)

    async def do_something(self):
        now = DT.now()
        now_str = now.strftime("%d/%m/%Y %H:%M:%S")
        message = "[{0}] {1} : Running this".format(inspect.stack()[0].function, now_str)
        print (message)
        self.write(message)

我希望网页更新为以下消息:
[do_something] 2019 年 4 月 27 日 23:42:08 :运行 这个
[do_something] 2019 年 4 月 27 日 23:42:18 :运行 这个

您不需要 spawn_callback。只需将 get 方法转换为异步协程和 minute_loop 上的 await

async def get(self):
    ...
    await self.minute_loop()

注意:网页不应该是长 运行 连接。如果你想用新数据更新网页,你应该考虑websockets。