我正在处理程序中执行websocket的write_message方法,我将报告一个错误。
class Test_Handler(BaseHandler):
@run_on_executor
def get(self):
host_name = 'Win10'
ws = WebSocketHandler.clients[host_name]['self']
ws.write_message(json.dumps({
'status': 203, # 状态201是为启动机器人
}))
return self.write({'status': 200})
File "D:\Anaconda3\lib\site-packages\tornado\websocket.py", line 256, in write_message
return self.ws_connection.write_message(message, binary=binary)
File "D:\Anaconda3\lib\site-packages\tornado\websocket.py", line 801, in write_message
fut = self._write_frame(True, opcode, message, flags=flags)
File "D:\Anaconda3\lib\site-packages\tornado\websocket.py", line 780, in _write_frame
return self.stream.write(frame)
File "D:\Anaconda3\lib\site-packages\tornado\iostream.py", line 536, in write
future = Future()
File "D:\Anaconda3\lib\asyncio\events.py", line 694, in get_event_loop
return get_event_loop_policy().get_event_loop()
File "D:\Anaconda3\lib\asyncio\events.py", line 602, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-0_0'.
答案 0 :(得分:0)
不得从另一个线程调用任何Tornado方法(IOLoop.add_callback
除外)。这包括执行者创建的线程。调用同步代码时使用执行程序;为Tornado编写的异步代码不需要它们,而且我认为没有理由在此代码段中使用一个。
通常,最好使用IOLoop.run_in_executor
而不是@run_on_executor
装饰器,因为它使异步和同步模式之间的转换更加明确。
答案 1 :(得分:0)
确保类Test_Handler
包含两个成员:
def __init__(self, *args, **kwargs):
self.executor = tornado.concurrent.futures.ThreadPoolExecutor(...)
self.io_loop = tornado.ioloop.IOLoop.current()