tornado - 在 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:运行此
解决方案
你不需要spawn_callback
。只需将该get
方法转换为异步协程并await
在minute_loop
.
async def get(self):
...
await self.minute_loop()
注意:网页不应该是长时间运行的连接。如果你想用新数据更新网页,你应该考虑 websockets。
推荐阅读
- angular2-nativescript - TabView 缓存或重新加载启动
- angular - 错误类型错误:无法读取属性“登录”
- python - 为什么 Visual Studio Code 不断更改工作目录?
- github-pages - Github pages 制作下载markdown文件
- angular - 角度变量不保存数据
- c# - 无法从 C# 下载 excel 文件
- owl - 在 Graphdb 中使用 Dataproperty 进行简单推理
- stanford-nlp - 管道定义上的类型初始化异常
- python - Pandas DataFrames KeyError:0
- cordova - 类星体框架。android开发模式下的ERR_CONNECTION_TIMED_OUT