tornado是一個異步非阻塞的WEB框架.它的異步非阻塞實際上就是用事件循環寫的。html
主要體如今2點:web
1. 做爲webserver能夠接收請求,同時支持異步處理請求。Django只能處理完成上一個請求後才能處理下一個請求。sql
2. 做爲客戶端能夠支持相似gevent,twisted這樣的異步IO,同時發送多個請求,而後等待請求結果。框架
安裝tornado異步
pip3 install tornado
Tornado實例函數
from tornado.httpclient import AsyncHTTPClient # 異步請求客戶端 from tornado.httpclient import HTTPRequest from tornado import ioloop # 監聽IO循環 def handle_response(response): """ 處理返回值內容(須要維護計數器,來中止IO循環),調用 ioloop.IOLoop.current().stop() :param response: """ if response.error: print("Error:", response.error) else: print(response.body) def func(): url_list = [ 'http://www.baidu.com', 'http://www.bing.com', ] for url in url_list: print(url) http_client = AsyncHTTPClient() # 異步發送請求 # 封裝請求的URL到HTTPRequest(url),執行完成後執行回調函數 http_client.fetch(HTTPRequest(url), handle_response) # 拿到一個IO循環並添加一個函數進去 ioloop.IOLoop.current().add_callback(func) # 函數執行且請求已經發送過去 ioloop.IOLoop.current().start() # 表示一直在等待請求的返回