tornado异步协程

Tornado的协程

Tornado的异步编程也主要体现在网络IO的异步上,即异步Web请求。

异步Web请求客户端

Tornado提供了一个异步Web请求客户端tornado.httpclient.AsyncHTTPClient用来进行异步Web请求。

fetch(request)

用于执行一个web请求request,并异步返回一个tornado.httpclient.HTTPResponse响应。

request可以是一个url,也可以是一个tornado.httpclient.HTTPRequest对象。如果是url地址,fetch方法内部会自己构造一个HTTPRequest对象。

HTTPRequest

HTTP请求类,HTTPRequest的构造函数可以接收众多构造参数,最常用的如下:

  • url (string) – 要访问的url,此参数必传,除此之外均为可选参数
  • method (string) – HTTP访问方式,如“GET”或“POST”,默认为GET方式
  • headers (HTTPHeaders or dict) – 附加的HTTP协议头
  • body – HTTP请求的请求体

HTTPResponse

HTTP响应类,其常用属性如下:

  • code: HTTP状态码,如 200 或 404
  • reason: 状态码描述信息
  • body: 响应体字符串
  • error: 异常(可有可无)

基于gen.coroutine的协程异步

from tornado import web,httpclient,gen,ioloop
import json
class Home(web.RequestHandler):
    @gen.coroutine
    def get(self):
        http = httpclient.AsyncHTTPClient()
        ip = "123.112.18.111"
        response = yield http.fetch("http://ip-api.com/json/%s?lang=zh-CN" % ip)
        if response.error:
            self.send_error(500)
        else:
            data = json.loads(response.body)
            if 'success' == data["status"]:
                self.write("国家:%s 省份: %s 城市: %s" % (data["country"], data["regionName"], data["city"]))
            else:
                self.write("查询IP信息错误")

# 设置路由列表
urls = [
    (r"/", Home),
]

if __name__ == "__main__":
    # 创建应用实例对象
    app = web.Application(urls, debug=True)
    # 设置监听的端口和地址
    app.listen(port=8888)
    # ioloop,全局的tornado事件循环,是服务器的引擎核心,start表示创建IO事件循环
    ioloop.IOLoop.current().start()

并行协程

from tornado import web,httpclient,gen,ioloop
import json
class Home(web.RequestHandler):
    @gen.coroutine
    def get(self):
        ips = ["123.112.18.111",
               "112.112.233.89",
               "119.112.23.3",
               "120.223.70.76"]
        rep1, rep2 = yield [self.get_ip_info(ips[0]), self.get_ip_info(ips[1])]
        self.write_response(ips[0], rep1)
        self.write_response(ips[1], rep2)
        rep_dict = yield dict(rep3=self.get_ip_info(ips[2]), rep4=self.get_ip_info(ips[3]))
        self.write_response(ips[2], rep_dict['rep3'])
        self.write_response(ips[3], rep_dict['rep4'])

    def write_response(self,ip, rep):
        if 'success' == rep["status"]:
            self.write("IP:%s 国家:%s 省份: %s 城市: %s<br>" % (ip,rep["country"], rep["regionName"], rep["city"]))
        else:
            self.write("查询IP信息错误<br>")
    @gen.coroutine
    def get_ip_info(self, ip):
        http = httpclient.AsyncHTTPClient()
        response = yield http.fetch("http://ip-api.com/json/%s?lang=zh-CN" % ip)
        if response.error:
            rep = {"status":"fail"}
        else:
            rep = json.loads(response.body)
        raise gen.Return(rep)  # 此处需要注意

# 设置路由列表
urls = [
    (r"/", Home),
]

if __name__ == "__main__":
    # 创建应用实例对象
    app = web.Application(urls, debug=True)
    # 设置监听的端口和地址
    app.listen(port=8888)
    # ioloop,全局的tornado事件循环,是服务器的引擎核心,start表示创建IO事件循环
    ioloop.IOLoop.current().start()

猜你喜欢

转载自blog.csdn.net/qq_45066628/article/details/112912503
今日推荐