zoukankan      html  css  js  c++  java
  • Python中的Asyncio 异步编程

    参考文档

    为什么要讲?

    • 这一部分的知识点不太容易学习
    • 异步相关话题和框架越来越多:例如:tornado fastapi django3.x asgi aiohttp 都是异步 -> 提升性能

    协程

    协程不是计算机提供的,程序员创造出来的。

    协程也可以称为微线程,是一种用户态内的上下文切换技术。简而言之,其实就是通过一个线程实现代码块相互切换执行。

    Python中实现协程的几种方式

    1. greenlet 早期模块
    2. yield 关键字
    3. asyncio 装饰器 (python3.4)
    4. asyncawait关键字 (python3.5) 【推荐】

    异步编程

    事件循环

    理解成一个死循环,去检测并执行某些代码

    伪代码

    任务列表 = [ 任务1, 任务2, 任务3,... ]
    while True:
        可执行的任务列表,已完成的任务列表 = 去任务列表中检查所有的任务,将'可执行'和'已完成'的任务返回
    
        for 就绪任务 in 已准备就绪的任务列表:
            执行已就绪的任务
        
        for 已完成的任务 in 已完成的任务列表:
            在任务列表中移除 已完成的任务
            
        如果 任务列表 中的任务都已完成,则终止循环
    
    import asyncio
    
    loop = asyncio.get_event_loop()		# 去生成/获取一个事件循环
    loop.run_until_complete('任务')		# 将`任务`放到`任务列表`
    

    快速上手

    协程函数:定义函数的时候async def 函数名

    协程对象:执行协程函数() 得到的返回值

    async def foo():
      # 协程函数
      pass
    
    
    result = foo()		# result 就是协程对象
    
    # 注意:执行`协程函数()` 创建协程对象,函数内部代码不会执行。
    

    如果想要执行协程函数内部代码,必须要将协程对象交给事件循环来处理

    import asyncio
    
    async def foo():
      # 协程函数
      print('执行了')
    
    
    result = foo()		# result 就是协程对象
    
    # 方式一:
    # loop = asyncio.get_event_loop()		# 去生成/获取一个事件循环
    # loop.run_until_complete(result)		# 将`任务`放到`任务列表`
    
    # 方式二:python3.7之后
    asyncio.run(result)
    

    await

    await + 可等待对象(协程对象、future、task对象 ----> IO等待)

    示例1

    import asyncio
    
    
    async def foo():
        print('来玩啊')
        response = await asyncio.sleep(2)   # 假设是一个网络请求
        print(f'结束: {response}')
    
    
    asyncio.run(foo())
    

    示例2

    import asyncio
    
    
    async def others():
        print("start")  # 2
        await asyncio.sleep(2)
        print('end')  # 3
        return '返回值'
    
    
    async def func():
        print("执行协程函数内部代码")  # 1
        # 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行。当前协程挂起时,事件循环可以去执行其他协程(任务)。
        response = await others()
        print("IO请求结束,结果为:", response)  # 4
    
    
    asyncio.run(func())
    

    示例3

    import asyncio
    
    
    async def others():
        print("start")
        await asyncio.sleep(2)
        print('end')
        return '返回值'
    
    
    async def func():
        print("执行协程函数内部代码")
        # 遇到IO操作挂起当前协程(任务),等IO操作完成之后再继续往下执行。当前协程挂起时,事件循环可以去执行其他协程(任务)。
        response1 = await others()
        print("1. IO请求结束,结果为:", response1)
        response2 = await others()
        print("2. IO请求结束,结果为:", response2)
    
    
    asyncio.run(func())
    

    await就是 等待对象 得到结果之后再继续往下执行

    await 其实就是在做 状态同步

    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 对象。

    本质上是将协程对象封装成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对象中并立即添加到事件循环的任务列表中,等待事件循环去执行(默认是就绪状态)。
        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())
    
    # 返回结果
    main开始
    main结束
    1
    1
    2
    2
    返回值 返回值
    

    示例2:推荐

    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()),
            asyncio.create_task(func())
        ]
        print("main结束")
        # 当执行某协程遇到IO操作时,会自动化切换执行其他任务。
        # 此处的await是等待所有协程执行完毕,并将所有协程的返回值保存到done
        # 如果设置了timeout值,则意味着此处最多等待的秒,完成的协程返回值写入到done中,未完成则写到pending中。
        done, pending = await asyncio.wait(task_list, timeout=None)
        print(done, pending)
    
    
    asyncio.run(main())
    
    # 返回结果
    main开始
    main结束
    1
    1
    2
    2
    {<Task finished coro=<func() done, defined at /Users/sunchangheng/Desktop/hello_python/async_demo/demo11_task02.py:4> result='返回值'>, <Task finished coro=<func() done, defined at /Users/sunchangheng/Desktop/hello_python/async_demo/demo11_task02.py:4> result='返回值'>} set()
    

    示例3:了解

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

    asyncio.Future对象

    A Futureis a special low-level awaitable object that represents an eventual result of an asynchronous operation.

    asyncio中的Future对象是一个相对更偏向底层的可对象,通常我们不会直接用到这个对象,而是直接使用Task对象来完成任务的并和状态的追踪。( Task 是 Futrue的子类 )

    Future为我们提供了异步编程中的 最终结果 的处理(Task类也具备状态处理的功能)。

    示例1

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

    concurrent.future.Future对象

    使用线程池、进程池实现异步操作时用的对象。

    示例1

    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)
    
    
    pool = ThreadPoolExecutor(max_workers=5)
    # 或 pool = ProcessPoolExecutor(max_workers=5)
    for i in range(10):
        fut = pool.submit(func, i)
        print(fut)
    

    其实,一般在程序开发中我们要么统一使用 asycio 的协程实现异步操作、要么都使用进程池和线程池实现异步操作。但如果 协程的异步进程池/线程池的异步 混搭时,那么就会用到此功能了。

    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)
        print('type', type(fut))
        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))
    

    异步迭代器

    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 is None:
                print('终止')
                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())
    

    异步上下文管理器

    """异步上下文管理器"""
    import asyncio
    
    
    class AsyncContextManager:
        def __init__(self):
            self.conn = None
    
        async def do_something(self):
            # 异步操作数据库
            return 666
    
        async def __aenter__(self):
            # 异步链接数据库
            print('异步链接数据库开始')
            self.conn = await asyncio.sleep(1)
            print('异步链接数据库结束')
            return self
    
        async def __aexit__(self, exc_type, exc, tb):
            # 异步关闭数据库链接
            print('异步关闭数据库连接开始')
            await asyncio.sleep(1)
            print('异步关闭数据库连接结束')
    
    
    async def func():
        async with AsyncContextManager() as f:
            result = await f.do_something()
            print(result)
    
    
    asyncio.run(func())
    

    uvloop

    Asyncio的事件循环的替代方案。uvloop事件循环效率大于Asyncio的事件循环

    pip install uvloop
    
    import asyncio
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    
    # 编写asyncio的代码,与之前写的代码一致。
    
    # 内部的事件循环自动化会变为uvloop
    asyncio.run(...)
    

    注意: asgi ---> uvicorn 内部就是用了uvloop

    实战案例

    异步操作redis

    当通过python去操作redis时,链接、设置值、获取值 这些都涉及网络IO请求,使用asycio异步的方式可以在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))
    

    异步MySQL

    pip 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='123456', 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('127.0.0.1', "123456"),
        execute('127.0.0.1', "123456"),
    ]
    asyncio.run(asyncio.wait(task_list))
    

    FastAPI

    安装uvicorn,本质上为web提供socket server的支持的asgi(一般支持异步称asgi、不支持异步称wsgi

    pip install fastapi
    pip install uvicorn		# asgi 基于 uvloop
    
    #!/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://127.0.0.1:6379', password=None, 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执行完毕,则会再次回到指定请求向下继续执行其功能代码。

    爬虫

    pip 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))
    
    
    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())
    
  • 相关阅读:
    Codeforces Round #595 (Div. 3) C题题解
    Educational Codeforces Round 83 (Rated for Div. 2)
    【算法竞赛进阶指南】Supermarket 贪心+并查集
    【算法竞赛进阶指南】字典树 The XOR Longest Path
    【算法竞赛进阶指南】字典树 The XOR Largest Pair
    【算法进阶指南】双端队列 DP+思维
    【算法进阶指南】蚯蚓 队列
    【2019 杭电多校第一场】Path 最短路+最小割
    【2017 ICPC 沈阳】G.Infinite Fraction Path 暴力优化
    【2017 CCPC 秦皇岛】A.Balloon Robot 思维
  • 原文地址:https://www.cnblogs.com/sunch/p/13590296.html
Copyright © 2011-2022 走看看