asyncio非同步程式設計(轉載於武沛齊老師)
作者:武沛齊
出處:http://www.cnblogs.com/wupeiqi/
不知道你是否發現,身邊聊非同步的人越來越多了,比如:FastAPI、Tornado、Sanic、Django 3、aiohttp等。
聽說非同步如何如何牛逼?效能如何吊炸天。。。。但他到底是咋回事呢?
本節要跟大家一起聊聊關於asyncio非同步的那些事!
視訊教程:https://study.163.com/instructor/3525856.htm
wiki同步:https://pythonav.com/wiki/
1.協程
想學asyncio,得先了解協程,協程是根本呀!
協程(Coroutine),也可以被稱為微執行緒,是一種使用者態內的上下文切換技術。簡而言之,其實就是通過一個執行緒實現程式碼塊相互切換執行。例如:
1 2 3 4 5 6 7 8 9 10 |
def func1():
print ( 1 )
...
print ( 2 )
def func2():
print ( 3 )
...
print ( 4 )
func1()
func2()
|
上述程式碼是普通的函式定義和執行,按流程分別執行兩個函式中的程式碼,並先後會輸出:1、2、3、4
。但如果介入協程技術那麼就可以實現函式見程式碼切換執行,最終輸入:1、3、2、4
。
在Python中有多種方式可以實現協程,例如:
- greenlet,是一個第三方模組,用於實現協程程式碼(Gevent協程就是基於greenlet實現)
- yield,生成器,藉助生成器的特點也可以實現協程程式碼。
- asyncio,在Python3.4中引入的模組用於編寫協程程式碼。
- async & awiat,在Python3.5中引入的兩個關鍵字,結合asyncio模組可以更方便的編寫協程程式碼。
1.1 greenlet
greentlet是一個第三方模組,需要提前安裝pip3 install greenlet
才能使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from greenlet import greenlet
def func1():
print ( 1 ) # 第1步:輸出 1
gr2.switch() # 第3步:切換到 func2 函式
print ( 2 ) # 第6步:輸出 2
gr2.switch() # 第7步:切換到 func2 函式,從上一次執行的位置繼續向後執行
def func2():
print ( 3 ) # 第4步:輸出 3
gr1.switch() # 第5步:切換到 func1 函式,從上一次執行的位置繼續向後執行
print ( 4 ) # 第8步:輸出 4
gr1 = greenlet(func1)
gr2 = greenlet(func2)
gr1.switch() # 第1步:去執行 func1 函式
|
注意:switch中也可以傳遞引數用於在切換執行時相互傳遞值。
1.2 yield
基於Python的生成器的yield和yield form關鍵字實現協程程式碼。
1 2 3 4 5 6 7 8 9 10 |
def func1():
yield 1
yield from func2()
yield 2
def func2():
yield 3
yield 4
f1 = func1()
for item in f1:
print (item)
|
注意:yield form關鍵字是在Python3.3中引入的。
1.3 asyncio
在Python3.4之前官方未提供協程的類庫,一般大家都是使用greenlet等其他來實現。在Python3.4釋出後官方正式支援協程,即:asyncio模組。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import asyncio
@asyncio .coroutine
def func1():
print ( 1 )
yield from asyncio.sleep( 2 ) # 遇到IO耗時操作,自動化切換到tasks中的其他任務
print ( 2 )
@asyncio .coroutine
def func2():
print ( 3 )
yield from asyncio.sleep( 2 ) # 遇到IO耗時操作,自動化切換到tasks中的其他任務
print ( 4 )
tasks = [
asyncio.ensure_future( func1() ),
asyncio.ensure_future( func2() )
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
|
注意:基於asyncio模組實現的協程比之前的要更厲害,因為他的內部還集成了遇到IO耗時操作自動切花的功能。
1.4 async & awit
async & awit 關鍵字在Python3.5版本中正式引入,基於他編寫的協程程式碼其實就是 上一示例 的加強版,讓程式碼可以更加簡便。
Python3.8之後@asyncio.coroutine
裝飾器就會被移除,推薦使用async & awit 關鍵字實現協程程式碼。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import asyncio
async def func1():
print ( 1 )
await asyncio.sleep( 2 )
print ( 2 )
async def func2():
print ( 3 )
await asyncio.sleep( 2 )
print ( 4 )
tasks = [
asyncio.ensure_future(func1()),
asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
|
1.5 小結
關於協程有多種實現方式,目前主流使用是Python官方推薦的asyncio模組和async&await關鍵字的方式,例如:在tonado、sanic、fastapi、django3 中均已支援。
接下來,我們也會針對asyncio模組
+async & await
關鍵字進行更加詳細的講解。
2.協程的意義
通過學習,我們已經瞭解到協程可以通過一個執行緒在多個上下文中進行來回切換執行。
但是,協程來回切換執行的意義何在呢?(網上看到很多文章舔協程,協程牛逼之處是哪裡呢?)
計算型的操作,利用協程來回切換執行,沒有任何意義,來回切換並儲存狀態反倒會降低效能。
IO型的操作,利用協程在IO等待時間就去切換執行其他任務,當IO操作結束後再自動回撥,那麼就會大大節省資源並提供效能,從而實現非同步程式設計(不等待任務結束就可以去執行其他程式碼)。
2.1 爬蟲案例
例如:用程式碼實現下載url_list
中的圖片。
- 方式一:同步程式設計實現
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 """
下載圖片使用第三方模組requests,請提前安裝:pip3 install requests
"""
import
requests
def
download_image(url):
print
(
"開始下載:"
,url)
# 傳送網路請求,下載圖片
response
=
requests.get(url)
print
(
"下載完成"
)
# 圖片儲存到本地檔案
file_name
=
url.rsplit(
'_'
)[
-
1
]
with
open
(file_name, mode
=
'wb'
) as file_object:
file_object.write(response.content)
if
__name__
=
=
'__main__'
:
url_list
=
[
'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg'
,
'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg'
,
'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
]
for
item
in
url_list:
download_image(item)
- 方式二:基於協程的非同步程式設計實現
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 """
下載圖片使用第三方模組aiohttp,請提前安裝:pip3 install aiohttp
"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import
aiohttp
import
asyncio
async
def
fetch(session, url):
print
(
"傳送請求:"
, url)
async with session.get(url, verify_ssl
=
False
) as response:
content
=
await response.content.read()
file_name
=
url.rsplit(
'_'
)[
-
1
]
with
open
(file_name, mode
=
'wb'
) as file_object:
file_object.write(content)
async
def
main():
async with aiohttp.ClientSession() as session:
url_list
=
[
'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg'
,
'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg'
,
'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
]
tasks
=
[asyncio.create_task(fetch(session, url))
for
url
in
url_list]
await asyncio.wait(tasks)
if
__name__
=
=
'__main__'
:
asyncio.run(main())
上述兩種的執行對比之後會發現,基於協程的非同步程式設計
要比同步程式設計
的效率高了很多。因為:
- 同步程式設計,按照順序逐一排隊執行,如果圖片下載時間為2分鐘,那麼全部執行完則需要6分鐘。
- 非同步程式設計,幾乎同時發出了3個下載任務的請求(遇到IO請求自動切換去傳送其他任務請求),如果圖片下載時間為2分鐘,那麼全部執行完畢也大概需要2分鐘左右就可以了。
2.2 小結
協程一般應用在有IO操作的程式中,因為協程可以利用IO等待的時間去執行一些其他的程式碼,從而提升程式碼執行效率。
生活中不也是這樣的麼,假設 你是一家制造汽車的老闆,員工點選裝置的【開始】按鈕之後,在裝置前需等待30分鐘,然後點選【結束】按鈕,此時作為老闆的你一定希望這個員工在等待的那30分鐘的時間去做點其他的工作。
3.非同步程式設計
基於async
&await
關鍵字的協程可以實現非同步程式設計,這也是目前python非同步相關的主流技術。
想要真正的瞭解Python中內建的非同步程式設計,根據下文的順序一點點來看。
3.1 事件迴圈
事件迴圈,可以把他當做是一個while迴圈,這個while迴圈在週期性的執行並執行一些任務
,在特定條件下終止迴圈。
1 2 3 4 5 6 7 8 9 |
# 虛擬碼
任務列表 = [ 任務 1 , 任務 2 , 任務 3 ,... ]
while True :
可執行的任務列表,已完成的任務列表 = 去任務列表中檢查所有的任務,將 '可執行' 和 '已完成' 的任務返回
for 就緒任務 in 已準備就緒的任務列表:
執行已就緒的任務
for 已完成的任務 in 已完成的任務列表:
在任務列表中移除 已完成的任務
如果 任務列表 中的任務都已完成,則終止迴圈
|
在編寫程式時候可以通過如下程式碼來獲取和建立事件迴圈。
1 2 |
import asyncio
loop = asyncio.get_event_loop()
|
3.2 協程和非同步程式設計
協程函式,定義形式為async def
的函式。
協程物件,呼叫協程函式所返回的物件。
1 2 3 4 5 |
# 定義一個協程函式
async def func():
pass
# 呼叫協程函式,返回一個協程物件
result = func()
|
注意:呼叫協程函式時,函式內部程式碼不會執行,只是會返回一個協程物件。
3.2.1 基本應用
程式中,如果想要執行協程函式的內部程式碼,需要事件迴圈
和協程物件
配合才能實現,如:
1 2 3 4 5 6 7 8 9 10 11 12 |
import asyncio
async def func():
print ( "協程內部程式碼" )
# 呼叫協程函式,返回一個協程物件。
result = func()
# 方式一
# loop = asyncio.get_event_loop() # 建立一個事件迴圈
# loop.run_until_complete(result) # 將協程當做任務提交到事件迴圈的任務列表中,協程執行完成之後終止。
# 方式二
# 本質上方式一是一樣的,內部先 建立事件迴圈 然後執行 run_until_complete,一個簡便的寫法。
# asyncio.run 函式在 Python 3.7 中加入 asyncio 模組,
asyncio.run(result)
|
這個過程可以簡單理解為:將協程
當做任務新增到事件迴圈
的任務列表,然後事件迴圈檢測列表中的協程
是否 已準備就緒(預設可理解為就緒狀態),如果準備就緒則執行其內部程式碼。
3.2.2 await
await是一個只能在協程函式中使用的關鍵字,用於遇到IO操作時掛起 當前協程(任務),當前協程(任務)掛起過程中 事件迴圈可以去執行其他的協程(任務),當前協程IO處理完成時,可以再次切換回來執行await之後的程式碼。程式碼如下:
示例1:
1 2 3 4 5 6 7 8 9 |
import asyncio
async def func():
print ( "執行協程函式內部程式碼" )
# 遇到IO操作掛起當前協程(任務),等IO操作完成之後再繼續往下執行。
# 當前協程掛起時,事件迴圈可以去執行其他協程(任務)。
response = await asyncio.sleep( 2 )
print ( "IO請求結束,結果為:" , response)
result = func()
asyncio.run(result)
|
示例2:
1 2 3 4 5 6 7 8 9 10 11 12 |
import asyncio
async def others():
print ( "start" )
await asyncio.sleep( 2 )
print ( 'end' )
return '返回值'
async def func():
print ( "執行協程函式內部程式碼" )
# 遇到IO操作掛起當前協程(任務),等IO操作完成之後再繼續往下執行。當前協程掛起時,事件迴圈可以去執行其他協程(任務)。
response = await others()
print ( "IO請求結束,結果為:" , response)
asyncio.run( func() )
|
示例3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import asyncio
async def others():
print ( "start" )
await asyncio.sleep( 2 )
print ( 'end' )
return '返回值'
async def func():
print ( "執行協程函式內部程式碼" )
# 遇到IO操作掛起當前協程(任務),等IO操作完成之後再繼續往下執行。當前協程掛起時,事件迴圈可以去執行其他協程(任務)。
response1 = await others()
print ( "IO請求結束,結果為:" , response1)
response2 = await others()
print ( "IO請求結束,結果為:" , response2)
asyncio.run( func() )
|
上述的所有示例都只是建立了一個任務,即:事件迴圈的任務列表中只有一個任務,所以在IO等待時無法演示切換到其他任務效果。
在程式想要建立多個任務物件,需要使用Task物件來實現。
3.2.3 Task物件
Tasksare used to schedule coroutinesconcurrently.
When a coroutine is wrapped into aTaskwith functions like
asyncio.create_task()
the coroutine is automatically scheduled to run soon。
Tasks用於併發排程協程,通過asyncio.create_task(協程物件)
的方式建立Task物件,這樣可以讓協程加入事件迴圈中等待被排程執行。除了使用asyncio.create_task()
函式以外,還可以用低層級的loop.create_task()
或ensure_future()
函式。不建議手動例項化 Task 物件。
本質上是將協程物件封裝成task物件,並將協程立即加入事件迴圈,同時追蹤協程的狀態。
注意:asyncio.create_task()
函式在 Python 3.7 中被加入。在 Python 3.7 之前,可以改用低層級的asyncio.ensure_future()
函式。
示例1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import asyncio
async def func():
print ( 1 )
await asyncio.sleep( 2 )
print ( 2 )
return "返回值"
async def main():
print ( "main開始" )
# 建立協程,將協程封裝到一個Task物件中並立即新增到事件迴圈的任務列表中,等待事件迴圈去執行(預設是就緒狀態)。
task1 = asyncio.create_task(func())
# 建立協程,將協程封裝到一個Task物件中並立即新增到事件迴圈的任務列表中,等待事件迴圈去執行(預設是就緒狀態)。
task2 = asyncio.create_task(func())
print ( "main結束" )
# 當執行某協程遇到IO操作時,會自動化切換執行其他任務。
# 此處的await是等待相對應的協程全都執行完畢並獲取結果
ret1 = await task1
ret2 = await task2
print (ret1, ret2)
asyncio.run(main())
|
示例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import asyncio
async def func():
print ( 1 )
await asyncio.sleep( 2 )
print ( 2 )
return "返回值"
async def main():
print ( "main開始" )
# 建立協程,將協程封裝到Task物件中並新增到事件迴圈的任務列表中,等待事件迴圈去執行(預設是就緒狀態)。
# 在呼叫
task_list = [
asyncio.create_task(func(), name = "n1" ),
asyncio.create_task(func(), name = "n2" )
]
print ( "main結束" )
# 當執行某協程遇到IO操作時,會自動化切換執行其他任務。
# 此處的await是等待所有協程執行完畢,並將所有協程的返回值儲存到done
# 如果設定了timeout值,則意味著此處最多等待的秒,完成的協程返回值寫入到done中,未完成則寫到pending中。
done, pending = await asyncio.wait(task_list, timeout = None )
print (done, pending)
asyncio.run(main())
|
注意:asyncio.wait
原始碼內部會對列表中的每個協程執行ensure_future從而封裝為Task物件,所以在和wait配合使用時task_list的值為[func(),func()]
也是可以的。
示例3:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import asyncio
async def func():
print ( "執行協程函式內部程式碼" )
# 遇到IO操作掛起當前協程(任務),等IO操作完成之後再繼續往下執行。當前協程掛起時,事件迴圈可以去執行其他協程(任務)。
response = await asyncio.sleep( 2 )
print ( "IO請求結束,結果為:" , response)
coroutine_list = [func(), func()]
# 錯誤:coroutine_list = [ asyncio.create_task(func()), asyncio.create_task(func()) ]
# 此處不能直接 asyncio.create_task,因為將Task立即加入到事件迴圈的任務列表,
# 但此時事件迴圈還未建立,所以會報錯。
# 使用asyncio.wait將列表封裝為一個協程,並呼叫asyncio.run實現執行兩個協程
# asyncio.wait內部會對列表中的每個協程執行ensure_future,封裝為Task物件。
done,pending = asyncio.run( asyncio.wait(coroutine_list) )
|
3.2.4 asyncio.Future物件
A
Future
is a speciallow-levelawaitable object that represents aneventual resultof an asynchronous operation.
asyncio中的Future物件是一個相對更偏向底層的可物件,通常我們不會直接用到這個物件,而是直接使用Task物件來完成任務的並和狀態的追蹤。( Task 是 Futrue的子類 )
Future為我們提供了非同步程式設計中的 最終結果 的處理(Task類也具備狀態處理的功能)。
示例1:
1 2 3 4 5 6 7 8 |
async def main():
# 獲取當前事件迴圈
loop = asyncio.get_running_loop()
# # 建立一個任務(Future物件),這個任務什麼都不幹。
fut = loop.create_future()
# 等待任務最終結果(Future物件),沒有結果則會一直等下去。
await fut
asyncio.run(main())
|
示例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import asyncio
async def set_after(fut):
await asyncio.sleep( 2 )
fut.set_result( "666" )
async def main():
# 獲取當前事件迴圈
loop = asyncio.get_running_loop()
# 建立一個任務(Future物件),沒繫結任何行為,則這個任務永遠不知道什麼時候結束。
fut = loop.create_future()
# 建立一個任務(Task物件),綁定了set_after函式,函式內部在2s之後,會給fut賦值。
# 即手動設定future任務的最終結果,那麼fut就可以結束了。
await loop.create_task(set_after(fut))
# 等待 Future物件獲取 最終結果,否則一直等下去
data = await fut
print (data)
asyncio.run(main())
|
Future物件本身函式進行繫結,所以想要讓事件迴圈獲取Future的結果,則需要手動設定。而Task物件繼承了Future物件,其實就對Future進行擴充套件,他可以實現在對應繫結的函式執行完成之後,自動執行set_result
,從而實現自動結束。
雖然,平時使用的是Task物件,但對於結果的處理本質是基於Future物件來實現的。
擴充套件:支援await 物件
語 法的物件課成為可等待物件,所以協程物件
、Task物件
、Future物件
都可以被成為可等待物件。
3.2.5 futures.Future物件
在Python的concurrent.futures
模組中也有一個Future物件,這個物件是基於執行緒池和程序池實現非同步操作時使用的物件。
1 2 3 4 5 6 7 8 9 10 11 12 |
port time
from concurrent.futures import Future
from concurrent.futures.thread import ThreadPoolExecutor
from concurrent.futures.process import ProcessPoolExecutor
def func(value):
time.sleep( 1 )
print (value)
pool = ThreadPoolExecutor(max_workers = 5 )
# 或 pool = ProcessPoolExecutor(max_workers=5)
for i in range ( 10 ):
fut = pool.submit(func, i)
print (fut)
|
兩個Future物件是不同的,他們是為不同的應用場景而設計,例如:concurrent.futures.Future
不支援await語法 等。
官方提示兩物件之間不同:
-
unlike asyncio Futures,
concurrent.futures.Future
instances cannot be awaited. -
asyncio.Future.result()
andasyncio.Future.exception()
do not accept thetimeoutargument. asyncio.Future.result()
andasyncio.Future.exception()
raise anInvalidStateError
exception when the Future is notdone.- Callbacks registered with
asyncio.Future.add_done_callback()
are not called immediately. They are scheduled withloop.call_soon()
instead. - asyncio Future is not compatible with the
concurrent.futures.wait()
andconcurrent.futures.as_completed()
functions.
在Python提供了一個將futures.Future
物件包裝成asyncio.Future
物件的函式asynic.wrap_future
。
接下里你肯定問:為什麼python會提供這種功能?
其實,一般在程式開發中我們要麼統一使用 asycio 的協程實現非同步操作、要麼都使用程序池和執行緒池實現非同步操作。但如果協程的非同步
和程序池/執行緒池的非同步
混搭時,那麼就會用到此功能了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import time
import asyncio
import concurrent.futures
def func1():
# 某個耗時操作
time.sleep( 2 )
return "SB"
async def main():
loop = asyncio.get_running_loop()
# 1. Run in the default loop's executor ( 預設ThreadPoolExecutor )
# 第一步:內部會先呼叫 ThreadPoolExecutor 的 submit 方法去執行緒池中申請一個執行緒去執行func1函式,並返回一個concurrent.futures.Future物件
# 第二步:呼叫asyncio.wrap_future將concurrent.futures.Future物件包裝為asycio.Future物件。
# 因為concurrent.futures.Future物件不支援await語法,所以需要包裝為 asycio.Future物件 才能使用。
fut = loop.run_in_executor( None , func1)
result = await fut
print ( 'default thread pool' , result)
# 2. Run in a custom thread pool:
# with concurrent.futures.ThreadPoolExecutor() as pool:
# result = await loop.run_in_executor(
# pool, func1)
# print('custom thread pool', result)
# 3. Run in a custom process pool:
# with concurrent.futures.ProcessPoolExecutor() as pool:
# result = await loop.run_in_executor(
# pool, func1)
# print('custom process pool', result)
asyncio.run(main())
|
應用場景:當專案以協程式的非同步程式設計開發時,如果要使用一個第三方模組,而第三方模組不支援協程方式非同步程式設計時,就需要用到這個功能,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import asyncio
import requests
async def download_image(url):
# 傳送網路請求,下載圖片(遇到網路下載圖片的IO請求,自動化切換到其他任務)
print ( "開始下載:" , url)
loop = asyncio.get_event_loop()
# requests模組預設不支援非同步操作,所以就使用執行緒池來配合實現了。
future = loop.run_in_executor( None , requests.get, url)
response = await future
print ( '下載完成' )
# 圖片儲存到本地檔案
file_name = url.rsplit( '_' )[ - 1 ]
with open (file_name, mode = 'wb' ) as file_object:
file_object.write(response.content)
if __name__ = = '__main__' :
url_list = [
'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg' ,
'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg' ,
'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
]
tasks = [download_image(url) for url in url_list]
loop = asyncio.get_event_loop()
loop.run_until_complete( asyncio.wait(tasks) )
|
3.2.6 非同步迭代器
什麼是非同步迭代器
實現了__aiter__()
和__anext__()
方法的物件。__anext__
必須返回一個awaitable物件。async for
會處理非同步迭代器的__anext__()
方法所返回的可等待物件,直到其引發一個StopAsyncIteration
異常。由PEP 492引入。
什麼是非同步可迭代物件?
可在async for
語句中被使用的物件。必須通過它的__aiter__()
方法返回一個asynchronous iterator。由PEP 492引入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import asyncio
class Reader( object ):
""" 自定義非同步迭代器(同時也是非同步可迭代物件) """
def __init__( self ):
self .count = 0
async def readline( self ):
# await asyncio.sleep(1)
self .count + = 1
if self .count = = 100 :
return None
return self .count
def __aiter__( self ):
return self
async def __anext__( self ):
val = await self .readline()
if val = = None :
raise StopAsyncIteration
return val
async def func():
# 建立非同步可迭代物件
async_iter = Reader()
# async for 必須要放在async def函式內,否則語法錯誤。
async for item in async_iter:
print (item)
asyncio.run(func())
|
非同步迭代器其實沒什麼太大的作用,只是支援了async for語法而已。
3.2.6 非同步上下文管理器
此種物件通過定義__aenter__()
和__aexit__()
方法來對async with
語句中的環境進行控制。由PEP 492引入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import asyncio
class AsyncContextManager:
def __init__( self ):
self .conn = conn
async def do_something( self ):
# 非同步操作資料庫
return 666
async def __aenter__( self ):
# 非同步連結資料庫
self .conn = await asyncio.sleep( 1 )
return self
async def __aexit__( self , exc_type, exc, tb):
# 非同步關閉資料庫連結
await asyncio.sleep( 1 )
async def func():
async with AsyncContextManager() as f:
result = await f.do_something()
print (result)
asyncio.run(func())
|
這個非同步的上下文管理器還是比較有用的,平時在開發過程中 開啟、處理、關閉 操作時,就可以用這種方式來處理。
3.3 小結
在程式中只要看到async
和await
關鍵字,其內部就是基於協程實現的非同步程式設計,這種非同步程式設計是通過一個執行緒在IO等待時間去執行其他任務,從而實現併發。
以上就是非同步程式設計的常見操作,內容參考官方文件。
- 中文版:https://docs.python.org/zh-cn/3.8/library/asyncio.html
- 英文字:https://docs.python.org/3.8/library/asyncio.html
4. uvloop
Python標準庫中提供了asyncio
模組,用於支援基於協程的非同步程式設計。
uvloop是 asyncio 中的事件迴圈的替代方案,替換後可以使得asyncio效能提高。事實上,uvloop要比nodejs、gevent等其他python非同步框架至少要快2倍,效能可以比肩Go語言。
安裝uvloop
1 |
pip3 install uvloop
|
在專案中想要使用uvloop替換asyncio的事件迴圈也非常簡單,只要在程式碼中這麼做就行。
1 2 3 4 5 6 |
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
# 編寫asyncio的程式碼,與之前寫的程式碼一致。
# 內部的事件迴圈自動化會變為uvloop
asyncio.run(...)
|
注意:知名的asgi uvicorn內部就是使用的uvloop的事件迴圈。
5.實戰案例
為了更好理解,上述所有示例的IO情況都是以asyncio.sleep
為例,而真實的專案開發中會用到很多IO的情況。
5.1 非同步Redis
當通過python去操作redis時,連結、設定值、獲取值 這些都涉及網路IO請求,使用asycio非同步的方式可以在IO等待時去做一些其他任務,從而提升效能。
安裝Python非同步操作redis模組
1 |
pip3 install aioredis
|
示例1:非同步操作redis。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import asyncio
import aioredis
async def execute(address, password):
print ( "開始執行" , address)
# 網路IO操作:建立redis連線
redis = await aioredis.create_redis(address, password = password)
# 網路IO操作:在redis中設定雜湊值car,內部在設三個鍵值對,即: redis = { car:{key1:1,key2:2,key3:3}}
await redis.hmset_dict( 'car' , key1 = 1 , key2 = 2 , key3 = 3 )
# 網路IO操作:去redis中獲取值
result = await redis.hgetall( 'car' , encoding = 'utf-8' )
print (result)
redis.close()
# 網路IO操作:關閉redis連線
await redis.wait_closed()
print ( "結束" , address)
asyncio.run(execute( 'redis://47.93.4.198:6379' , "root!2345" ))
|
示例2:連線多個redis做操作(遇到IO會切換其他任務,提供了效能)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import asyncio
import aioredis
async def execute(address, password):
print ( "開始執行" , address)
# 網路IO操作:先去連線 47.93.4.197:6379,遇到IO則自動切換任務,去連線47.93.4.198:6379
redis = await aioredis.create_redis_pool(address, password = password)
# 網路IO操作:遇到IO會自動切換任務
await redis.hmset_dict( 'car' , key1 = 1 , key2 = 2 , key3 = 3 )
# 網路IO操作:遇到IO會自動切換任務
result = await redis.hgetall( 'car' , encoding = 'utf-8' )
print (result)
redis.close()
# 網路IO操作:遇到IO會自動切換任務
await redis.wait_closed()
print ( "結束" , address)
task_list = [
execute( 'redis://47.93.4.197:6379' , "root!2345" ),
execute( 'redis://47.93.4.198:6379' , "root!2345" )
]
asyncio.run(asyncio.wait(task_list))
|
更多redis操作參考aioredis官網:https://aioredis.readthedocs.io/en/v1.3.0/start.html
5.2 非同步MySQL
當通過python去操作MySQL時,連線、執行SQL、關閉都涉及網路IO請求,使用asycio非同步的方式可以在IO等待時去做一些其他任務,從而提升效能。
安裝Python非同步操作redis模組
1 |
pip3 install aiomysql
|
示例1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import asyncio
import aiomysql
async def execute():
# 網路IO操作:連線MySQL
conn = await aiomysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , password = '123' , db = 'mysql' , )
# 網路IO操作:建立CURSOR
cur = await conn.cursor()
# 網路IO操作:執行SQL
await cur.execute( "SELECT Host,User FROM user" )
# 網路IO操作:獲取SQL結果
result = await cur.fetchall()
print (result)
# 網路IO操作:關閉連結
await cur.close()
conn.close()
asyncio.run(execute())
|
示例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import asyncio
import aiomysql
async def execute(host, password):
print ( "開始" , host)
# 網路IO操作:先去連線 47.93.40.197,遇到IO則自動切換任務,去連線47.93.40.198:6379
conn = await aiomysql.connect(host = host, port = 3306 , user = 'root' , password = password, db = 'mysql' )
# 網路IO操作:遇到IO會自動切換任務
cur = await conn.cursor()
# 網路IO操作:遇到IO會自動切換任務
await cur.execute( "SELECT Host,User FROM user" )
# 網路IO操作:遇到IO會自動切換任務
result = await cur.fetchall()
print (result)
# 網路IO操作:遇到IO會自動切換任務
await cur.close()
conn.close()
print ( "結束" , host)
task_list = [
execute( '47.93.40.197' , "root!2345" ),
execute( '47.93.40.197' , "root!2345" )
]
asyncio.run(asyncio.wait(task_list))
|
5.3 FastAPI框架
FastAPI是一款用於構建API的高效能web框架,框架基於Python3.6+的type hints
搭建。
接下里的非同步示例以FastAPI
和uvicorn
來講解(uvicorn是一個支援非同步的asgi)。
安裝FastAPI web 框架,
1 |
pip3 install fastapi
|
安裝uvicorn,本質上為web提供socket server的支援的asgi(一般支援非同步稱asgi、不支援非同步稱wsgi)
1 |
pip3 install uvicorn
|
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import asyncio
import uvicorn
import aioredis
from aioredis import Redis
from fastapi import FastAPI
app = FastAPI()
REDIS_POOL = aioredis.ConnectionsPool( 'redis://47.193.14.198:6379' , password = "root123" , minsize = 1 , maxsize = 10 )
@app .get( "/" )
def index():
""" 普通操作介面 """
return { "message" : "Hello World" }
@app .get( "/red" )
async def red():
""" 非同步操作介面 """
print ( "請求來了" )
await asyncio.sleep( 3 )
# 連線池獲取一個連線
conn = await REDIS_POOL.acquire()
redis = Redis(conn)
# 設定值
await redis.hmset_dict( 'car' , key1 = 1 , key2 = 2 , key3 = 3 )
# 讀取值
result = await redis.hgetall( 'car' , encoding = 'utf-8' )
print (result)
# 連線歸還連線池
REDIS_POOL.release(conn)
return result
if __name__ = = '__main__' :
uvicorn.run( "luffy:app" , host = "127.0.0.1" , port = 5000 , log_level = "info" )
|
在有多個使用者併發請求的情況下,非同步方式來編寫的介面可以在IO等待過程中去處理其他的請求,提供效能。
例如:同時有兩個使用者併發來向介面http://127.0.0.1:5000/red
傳送請求,服務端只有一個執行緒,同一時刻只有一個請求被處理。 非同步處理可以提供併發是因為:當檢視函式在處理第一個請求時,第二個請求此時是等待被處理的狀態,當第一個請求遇到IO等待時,會自動切換去接收並處理第二個請求,當遇到IO時自動化切換至其他請求,一旦有請求IO執行完畢,則會再次回到指定請求向下繼續執行其功能程式碼。
5.4 爬蟲
在編寫爬蟲應用時,需要通過網路IO去請求目標資料,這種情況適合使用非同步程式設計來提升效能,接下來我們使用支援非同步程式設計的aiohttp模組來實現。
安裝aiohttp模組
1 |
pip3 install aiohttp
|
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import aiohttp
import asyncio
async def fetch(session, url):
print ( "傳送請求:" , url)
async with session.get(url, verify_ssl = False ) as response:
text = await response.text()
print ( "得到結果:" , url, len (text))
async def main():
async with aiohttp.ClientSession() as session:
url_list = [
'https://python.org' ,
'https://www.baidu.com' ,
'https://www.pythonav.com'
]
tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
await asyncio.wait(tasks)
if __name__ = = '__main__' :
asyncio.run(main())
|
總結
為了提升效能越來越多的框架都在向非同步程式設計靠攏,例如:sanic、tornado、django3.0、django channels元件 等,用更少資源可以做處理更多的事,何樂而不為呢。