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.web.asynchronous # 该装饰器的意思是:当get方法结束时,不关闭连接,也不发送响应,只有明确调用finish()时,才返回响应 def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch( "https://rdnsdb.com/api/rdns/?ip=14.130.112.24", callback=self.on_response ) # 到这里,get方法就结束了 def on_response(self, response): if response.error: self.send_error(500) else: data = json.loads(response.body) if data["status"]: self.write(data["data"]) else: self.write("查询IP信息错误") # 发送响应,结束请求处理 self.finish() 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()
参考:https://blog.51cto.com/u_15294985/5140166
使用回调异步的步骤:
1、添加装饰器asynchronous
2、使用异步HTTPClient
3、编写回调函数
4、在回调函数里添加finish