源於自己折騰的一個小 Flask 項目中,後臺需訪問多個 HTTP 服務,目前採用 ThreadPoolExecutor 多線程的方式處理的。但因訪問 HTTP 服務有前後關聯關係,如得到請求 A 的結果後再訪問 B,這似乎用 Promise.then().then() 編程方式更合適些。於是巡着這一路子,翻出 Python 的各種相關部件來,比如 Python 對 coroutine(協程) 的支持,asyncio, 及後面的 async/await 關鍵子,aiohttp 組件,requests 的 async 替代品有 aiohttp, grequests, 和 httpx,aiohttp 可替代 Flask, 最後竟然找到了一個更徹底的 Flask 的 Async 版本 Quart。
Python 3.4 引入了 asyncio 模塊,基於生成器和 @asyncio.coroutine 的方式來支持 coroutine(協程), 到 Python 3.5 後有了 async/await 關鍵字,協程的實現變得更爲簡單。Python 3.4 使用 coroutine 的方式我們跳過,直接看