使用tornado报错 RuntimeError: Cannot run the event loop while another loop is running

 1.这里只是写了个简单的demo1,来记录为什么报错,见下面代码

# demo1.py

import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import tornado.httpclient


from tornado.options import define, options
define("port", default=8989, help="run on the given port", type=int)


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        client = tornado.httpclient.HTTPClient()
        response = client.fetch("https://www.baidu.com")
        print(response.body)
        self.write("ok")


if __name__ == '__main__':

    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers=[
            (r"/", IndexHandler)
        ],
        debug=True,

    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

正是在tornado的服务里面(存在ioloop循环)使用了HTTPClient,所以才报错了,这是因为在tornado 5.0以后只能在tornado服务中使用异步客户端AsyncHTTPClient,

解决使用同步客户端的问题是可以使用python的requests包

2.如果像下面这样,直接使用是没有问题的(不使用ioloop循环)

def h():
    http_client = tornado.httpclient.HTTPClient()
    try:
        response = http_client.fetch("https://www.baidu.com")
        print(response.body)
    except tornado.httpclient.HTTPError as e:
        # HTTPError is raised for non-200 responses; the response
        # can be found in e.response.
        print("Error: " + str(e))
    except Exception as e:
        # Other errors are possible, such as IOError.
        print("Error: " + str(e))
    http_client.close()

h()

3.如果想在tornado(版本5.0以后)服务中使用客户端,那么只能使用AsyncHTTPClient,如下

import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import tornado.httpclient


from tornado.options import define, options
define("port", default=8989, help="run on the given port", type=int)


class IndexHandler(tornado.web.RequestHandler):
    async def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = await client.fetch("https://www.baidu.com")
        print(response.body)
        self.write("ok")


if __name__ == '__main__':

    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers=[
            (r"/", IndexHandler)
        ],
        debug=True,

    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章