Tornado5 执行线程时报错:RuntimeError: There is no current event loop in thread 'Thread-1'.

最近将tornado 4.5.3升级到tornado 5.1 后执行下面threading时候报错:

报错内容 :RuntimeError: There is no current event loop in thread 'Thread-1'.

#!/usr/bin/env python3

import threading
import tornado.ioloop
import tornado.web
from tornado import gen

class RequestHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    @gen.coroutine
    def get(self, path):
        self.write("Test")
        self.finish()

class WebServer(threading.Thread):
    def run(self):
        application = tornado.web.Application([
            (r"/(.*)", RequestHandler)])
        application.listen(12345)
        tornado.ioloop.IOLoop.instance().start()

WebServer().start()

但在tornado 4.5.3上并没有问题。

github上面给出了以下解决方案:

https://github.com/tornadoweb/tornado/issues/2352

 我们可以使用asyncio.new_event_loop函数建立一个新的事件循环,并使用asyncio.set_event_loop设置全局的事件循环,这时候就可以多次运行异步的事件循环了,不过最好保存默认的asyncio.get_event_loop并在事件循环结束的时候还原回去。

#!/usr/bin/env python3

import threading
import tornado.ioloop
import tornado.web
from tornado import gen
import asyncio

class RequestHandler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    @gen.coroutine
    def get(self, path):
        self.write("Test")
        self.finish()

class WebServer(threading.Thread):
    def run(self):

        # tornado 5 中引入asyncio.set_event_loop即可
        asyncio.set_event_loop(asyncio.new_event_loop())

        application = tornado.web.Application([
            (r"/(.*)", RequestHandler)])
        application.listen(12345)
        tornado.ioloop.IOLoop.instance().start()

WebServer().start()

其他参考推荐:

https://stackoverflow.com/questions/32598231/asyncio-runtimeerror-event-loop-is-closed

https://github.com/tornadoweb/tornado/issues/2352

你可能感兴趣的:(web)