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): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch( "https://rdnsdb.com/api/rdns/?ip=14.130.112.24", ) if response.error: self.send_error(500) else: data = json.loads(response.body) if data["status"]: self.write(data["data"]) else: self.write("查询IP信息错误") 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()
协程异步使用步骤:
1、使用装饰器
@tornado.gen.coroutine
2、使用yield
拆分异步请求:
# -*- 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): # 异步调用 rep = yield self.get_ip_info("14.130.112.24") if rep["status"]: self.write(rep["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()