PEP492引入了native coroutine之后,增加了Python的书写异步代码的表达能力。Coroutine存在的意义之一是让异步代码看起跟同步代码类似,方便书写以及阅读。但是本质上,Coroutine和异步编程中的回调函数在功能上其实是一样的,需要某些触发条件才能被执行。
异步编程中的另一个重要概念是future。既然是异步,那么就意味着代码不会立马执行,也无法立马获取代码的执行结果,需要等待异步代码执行完成才能获取其结果。各种future就是用来表示那些不能立马获取到的结果。
Async IO in Python: A Complete Walkthrough
如果想了解asyncio,那么Brad Solomon写的这篇Async IO in Python: A Complete Walkthrough很有参考意义。文章中谈到了asynciocongPython3.4到3.7的演化,并举了许多例子说明如何使用asyncio。另外还谈到Parallelism、Multiprocessing、Cocurrency、Threading、Cooperative Multitasking种种概念。
最重要的是文章的末尾列举了很多参考链接,可以供深入了解asyncio。
Python Concurrency: Making sense of asyncio
这篇文章写得也非常好,对asyncio有比较详细的介绍。特别是其中针对future的介绍,以及针对run_coroutine_threadsafe()的例子,特别使人受启发。
基于asyncio的web框架
- Tornado,老牌基于asyncio的框架
- Quant,基于asyncio,但是模拟的是Flask的API
- Sanic,新派基于asyncio的框架
- Vibora,号称新能比Sanic快
- Starlette,同样是新派基于asyncio的框架
- FastAPI,基于Starlette,势头很足
其他
- Overview of Async IO in Python 3.7
- Guide to Concurrency in Python with Asyncio
- https://github.com/timofurrer/awesome-asyncio
- Concurrency with Python: Why?
- Using Asyncio in Python: Understanding Python’s Asynchronous Programming Features 1st Edition
- https://en.wikipedia.org/wiki/Coroutine#Implementations_for_Python
- aiohttp - Http client/server for asyncio (PEP-3156).
- Curio, The coroutine concurrency library.
- Trio, Pythonic async I/O for humans and snake people.
- Top 5 Asynchronous Web Frameworks for Python
- TOP Fast Python Web Frameworks in 2019
- https://stackoverflow.com/questions/49482969/what-is-the-core-difference-between-asyncio-and-trio
(本篇完)