Python 協程 & asyncio & 異步編程

  • 第一部分:協程。
  • 第二部分:asyncio模塊進行異步編程。
  • 第三部分:實戰案例。

1.協程

協程不是計算機提供,程序員人爲創造。

協程(Coroutine),也可以被稱爲微線程,是一種用戶態內的上下文切換技術。簡而言之,其實就是通過一個線程實現代碼塊相互切換執行。例如

def func1():
	print(1)
    ...
	print(2)
	
def func2():
	print(3)
    ...
	print(4)

func1()
func2()

實現協程有這麼幾種方法:

  • greenlet,早期模塊。
  • yield關鍵字。
  • asyncio裝飾器(py3.4)
  • async、await關鍵字(py3.5)【推薦】

1.1 greenlet實現協程

pip3 install greenlet
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 函數

1.2 yield關鍵字

def func1():
    yield 1
    yield from func2()
    yield 2


def func2():
    yield 3
    yield 4


f1 = func1()
for item in f1:
    print(item)

1.3 asyncio

在python3.4及之後的版本。

import asyncio

@asyncio.coroutine
def func1():
    print(1)
    # 網絡IO請求:下載一張圖片
    yield from asyncio.sleep(2)  # 遇到IO耗時操作,自動化切換到tasks中的其他任務
    print(2)


@asyncio.coroutine
def func2():
    print(3)
    # 網絡IO請求:下載一張圖片
    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))

注意:遇到IO阻塞自動切換

1.4 async & await關鍵字

在python3.5及之後的版本。

import asyncio

async def func1():
    print(1)
    # 網絡IO請求:下載一張圖片
    await asyncio.sleep(2)  # 遇到IO耗時操作,自動化切換到tasks中的其他任務
    print(2)


async def func2():
    print(3)
    # 網絡IO請求:下載一張圖片
    await 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))

2.協程意義

在一個線程中如果遇到IO等待時間,線程不會傻傻等,利用空閒的時候再去幹點其他事。

案例:去下載三張圖片(網絡IO)。

  • 普通方式(同步)

    """ 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)
    

    協程方式(異步)

    """
    下載圖片使用第三方模塊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)
            print('下載完成',url)
    
    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() )
    

    3.異步編程

    3.1 事件循環

    理解成爲一個死循環 ,去檢測並執行某些代碼。

    # 僞代碼
    
    任務列表 = [ 任務1, 任務2, 任務3,... ]
    
    while True:
        可執行的任務列表,已完成的任務列表 = 去任務列表中檢查所有的任務,將'可執行'和'已完成'的任務返回
        
        for 就緒任務 in 可執行的任務列表:
            執行已就緒的任務
            
        for 已完成的任務 in 已完成的任務列表:
            在任務列表中移除 已完成的任務
    
    	如果 任務列表 中的任務都已完成,則終止循環
    
    import asyncio
    
    # 去生成或獲取一個事件循環
    loop = asyncio.get_event_loop()
    
    # 將任務放到`任務列表`
    loop.run_until_complete(任務)
    

    3.2 快速上手

    協程函數,定義函數時候 async def 函數名 

    協程對象,執行 協程函數() 得到的協程對象。

    async def func():
        pass
    
    result = func()
    

    注意:執行協程函數創建協程對象,函數內部代碼不會執行。

    如果想要運行協程函數內部代碼,必須要講協程對象交給事件循環來處理。

    import asyncio 
    
    async def func():
        print("快來搞我吧!")
    
    result = func()
    
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete( result )
    asyncio.run( result ) # python3.7 
    

    3.3 await
    await + 可等待的對象(協程對象、Future、Task對象 -> IO等待)

    示例1:

    import asyncio
    
    async def func():
        print("來玩呀")
        response = await asyncio.sleep(2)
        print("結束",response)
    
    asyncio.run( func() )
    

    示例2:

    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() )
    

    await就是等待對象的值得到結果之後再繼續向下走。

    3.4 Task對象

    Tasks are used to schedule coroutines concurrently.
    
    When a coroutine is wrapped into a Task with 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 對象。

    注意:asyncio.create_task() 函數在 Python 3.7 中被加入。在 Python 3.7 之前,可以改用低層級的 asyncio.ensure_future() 函數。

    示例1:
     

    import asyncio
    
    
    async def func():
        print(1)
        await asyncio.sleep(2)
        print(2)
        return "返回值"
    
    
    async def main():
        print("main開始")
    	
     	# 創建Task對象,將當前執行func函數任務添加到事件循環。
        task1 = asyncio.create_task( func() )
    	
        # 創建Task對象,將當前執行func函數任務添加到事件循環。
        task2 = asyncio.create_task( func() )
    
        print("main結束")
    
        # 當執行某協程遇到IO操作時,會自動化切換執行其他任務。
        # 此處的await是等待相對應的協程全都執行完畢並獲取結果
        ret1 = await task1
        ret2 = await task2
        print(ret1, ret2)
    
    
    asyncio.run( main() )
    

    示例2:

    import asyncio
    
    
    async def func():
        print(1)
        await asyncio.sleep(2)
        print(2)
        return "返回值"
    
    
    async def main():
        print("main開始")
    
        task_list = [
            asyncio.create_task(func(), name='n1'),
            asyncio.create_task(func(), name='n2')
        ]
    
        print("main結束")
    
        done, pending = await asyncio.wait(task_list, timeout=None)
        print(done)
    
    
    asyncio.run(main())
    

    示例3:

    import asyncio
    
    
    async def func():
        print(1)
        await asyncio.sleep(2)
        print(2)
        return "返回值"
    
    
    task_list = [
        func(),
    	func(), 
    ]
    
    done,pending = asyncio.run( asyncio.wait(task_list) )
    print(done)
    

    3.5 asyncio.Future對象
    A Futureis a special low-level awaitable object that represents an eventual result of an asynchronous operation.

    Task繼承Future,Task對象內部await結果的處理基於Future對象來的。

    示例1:
     

    async def main():
        # 獲取當前事件循環
        loop = asyncio.get_running_loop()
    
        # 創建一個任務(Future對象),這個任務什麼都不幹。
        fut = loop.create_future()
    
        # 等待任務最終結果(Future對象),沒有結果則會一直等下去。
        await fut
    
    asyncio.run( main() )
    

    示例2:

    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() )
    

    3.5 concurrent.futures.Future對象

    使用線程池、進程池實現異步操作時用到的對象。

    import 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)
        return 123
    
    # 創建線程池
    pool = ThreadPoolExecutor(max_workers=5)
    
    # 創建進程池
    # pool = ProcessPoolExecutor(max_workers=5)
    
    
    for i in range(10):
        fut = pool.submit(func, i)
        print(fut)
    

    以後寫代碼可能會存在交叉時間。例如:crm項目80%都是基於協程異步編程 + MySQL(不支持)【線程、進程做異步編程】。

    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() )
    

    案例:asyncio + 不支持異步的模塊

    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.7 異步迭代器
    什麼是異步迭代器

    實現了 __aiter__() 和 __anext__() 方法的對象。__anext__ 必須返回一個 awaitable 對象。async for 會處理異步迭代器的 __anext__() 方法所返回的可等待對象,直到其引發一個 StopAsyncIteration 異常。由 PEP 492 引入。

    什麼是異步可迭代對象?

    可在 async for 語句中被使用的對象。必須通過它的 __aiter__() 方法返回一個 asynchronous iterator。由 PEP 492 引入。
     

    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():
        obj = Reader()
        async for item in obj:
            print(item)
            
    asyncio.run( func() )
    

    3.8 異步上下文管理器

    此種對象通過定義 __aenter__()  __aexit__() 方法來對 async with 語句中的環境進行控制。由 PEP 492 引入。

    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() )
    

    4.uvloop

    是asyncio的事件循環的替代方案。事件循環 > 默認asyncio的事件循環。

    pip3 install uvloop
    
    import asyncio
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    
    # 編寫asyncio的代碼,與之前寫的代碼一致。
    
    # 內部的事件循環自動化會變爲uvloop
    asyncio.run(...)
    

    注意:一個asgi -> uvicorn 內部使用的就是uvloop

    5.實戰案例

    5.1 異步redis

    在使用python代碼操作redis時,鏈接/操作/斷開都是網絡IO。

    pip3 install aioredis
    

    示例1:

    #!/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:

    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))
    

    5.2 異步MySQL

    pip3 install aiomysql
    

    示例1:

    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:

    #!/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.41.197', "root!2345"),
        execute('47.93.40.197', "root!2345")
    ]
    
    asyncio.run(asyncio.wait(task_list))
    

    5.3 FastAPI框架

    安裝

    pip3 install fastapi
    pip3 install uvicorn (asgi內部基於uvloop)
    

    示例: luffy.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import asyncio
    
    import uvicorn
    import aioredis
    from aioredis import Redis
    from fastapi import FastAPI
    
    app = FastAPI()
    
    # 創建一個redis連接池
    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")
    

    5.4 爬蟲

    pip3 install aiohttp
    
    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))
            return 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]
    
            done,pending = await asyncio.wait(tasks)
    
    
    if __name__ == '__main__':
        asyncio.run( main() )
    

    總結

    最大的意義:通過一個線程利用其IO等待時間去做一些其他事情。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章