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

本文探讨了在Tornado框架中使用HTTPClient进行同步请求时出现的问题及解决方案,介绍了如何在Tornado服务中正确使用异步客户端AsyncHTTPClient,以及在不使用ioloop循环时直接使用HTTPClient的方法。

 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值