tornado异步之并行协程

# -*- coding: utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient

import json


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


class IndexHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        # 异步调用
        ips = [
            "14.130.112.24", "15.130.112.24", "16.130.112.24", "17.130.112.24"
        ]

        rep1, rep2 = yield [self.get_ip_info(ips[0]), self.get_ip_info(ips[1])]
        rep34_dict = yield dict(rep3=self.get_ip_info(ips[2]), rep4=self.get_ip_info(ips[3]))

        self.write_response(ips[0], rep1)
        self.write_response(ips[1], rep2)
        self.write_response(ips[2], rep34_dict["rep3"])
        self.write_response(ips[3], rep34_dict["rep4"])

    def write_response(self, ip, response):
        self.write(ip)
        self.write(":<br/>")
        if response["status"]:
            self.write(response["data"])
        else:
            self.write("查询IP信息错误")

    # 将异步web请求独立出来
    @tornado.gen.coroutine
    def get_ip_info(self, ip):
        http = tornado.httpclient.AsyncHTTPClient()
        response = yield http.fetch(
            "https://rdnsdb.com/api/rdns/?ip=" + ip,
        )
        if response.error:
            rep = {"status": False}
        else:
            rep = json.loads(response.body)

        raise tornado.gen.Return(rep)


if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

 

posted @ 2022-07-13 18:48  道霖  阅读(57)  评论(0编辑  收藏  举报