首页 > 解决方案 > 在 spawn_callback 中使用异步写入会导致 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] 27/04/2019 23:42:08:运行此
[do_something] 27/04/2019 23:42:18:运行此

标签: tornado

解决方案


你不需要spawn_callback。只需将该get方法转换为异步协程并awaitminute_loop.

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

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


推荐阅读