使用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()

 

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