【asyncio】异步编程知识总结

1. 基础概念

1.1 协程概念

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

实现协程的几种方法:

  • greentlet ,手动switch切换
  • yield关键字
  • asyncio装饰器(py3.4+),遇到IO自动切换。
  • async、await他关键字(py3.5,推荐)

协程的目的是通过一个线程利用其IO等待的时候,再去干点别的事情,别闲着!

1.2 事件循环

可以把事件循环当作一个while True循环,监测并执行某些代码。

# 伪代码
任务列表 = [ 任务1, 任务2, 任务3, ... ]
while True:
	可执行的任务列表,已完成的任务列表 = 去任务列表中检查所有任务,将“可执行”和“已完成”的任务返回。
	for 就绪任务 in 可执行的任务列表:
		执行已就绪的任务
	for 已完成的任务 in 已完成的任务列表
		在任务列表中移除已完成的任务
	如果 任务列表 中的任务都已完成,则终止循环
import asyncio

# 去生成或获取一个事件循环
loop = asyncio.get_event_loop()
# 将任务放到任务列表
loop.run_until_complete(任务)

1.3 协程函数和协程对象

协程函数: 定义函数格式为async def 函数名
协程对象: 协程函数() 得到的对象。

async def func():
	pass

result = func()

注意: result = func()创建协程对象,函数内部代码不会执行

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

import asyncio

async def func():
	print('111111')

result = func()

loop = asyncio.get_event_loop()
loop.run_until_complete(result)

1.4 await关键字

await后跟可等待对象,可等待对象包括协程对象FutureTask对象,这些都是IO等待。等IO操作完成之后再继续往下执行,当前协程(任务)挂起时,事件循环可以执行其他协程(任务)。

同一个协程任务中,多个await,会依次等待等待对象执行完成;不同协程任务中,遇到await会交替执行。

案例1:

import asyncio


async def func1():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "func1"


async def test1():
    print("执行协程函数test1内部代码")
    resp = await func1()
    print("IO请求结束test1,结果为: ", resp)
    resp = await func1()
    print("IO请求结束test1,结果为: ", resp)


tasks = [
    asyncio.ensure_future(test1())
]


loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

运行结果:
在这里插入图片描述

案例2:

import asyncio


async def func1():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "func1"


async def func2():
    print(3)
    await asyncio.sleep(2)
    print(4)
    return "func2"


async def test1():
    print("执行协程函数test1内部代码")
    resp = await func1()
    print("IO请求结束test1,结果为: ", resp)


async def test2():
    print("执行协程函数test2内部代码")
    resp = await func2()
    print("IO请求结束test2,结果为: ", resp)


tasks = [
    asyncio.ensure_future(test1()),
    asyncio.ensure_future(test2())
]


loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

运行结果:
在这里插入图片描述

1.5 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.

Task被用来在事件循环中添加多个任务的。

当协程包装到具有asyncio.create_task()等函数的任务中时,会自动地添加到事件循环中等待被调度执行。除了使用asynico.create_task()函数以外,还可以用底层级的loop.create_create_task()ensure_future()函数

注意: asynico.create_task()函数在py3.7中被加入。在py3.7之前,可以改用低层级的asyncio.ensure_future()函数。

create_task源码,获取正在运行的事件循环,然后在事件循环里把任务core添加进去,最后返回一个Task对象。

def create_task(coro, *, name=None):
    """Schedule the execution of a coroutine object in a spawn task.

    Return a Task object.
    """
    loop = events.get_running_loop()
    task = loop.create_task(coro)
    _set_task_name(task, name)
    return task

案例1:

import asyncio


async def func1(n):
    print(n)
    await asyncio.sleep(2)
    print(n)
    return f"func{n}"


async def main():
    print('开始')
	# 自动加入到事件循环里
    task1 = asyncio.create_task(func1(1))
    # 自动加入到事件循环里
    task2 = asyncio.create_task(func1(2))

    print('结束')
    result1 = await task1
    result2 = await task2
    print(result1, result2)


asyncio.run(main())

在这里插入图片描述

案例2:

import asyncio


async def func1():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "func1"


async def main():
    print('开始')
    task_list = [
    	# 自动加入到事件循环里
        asyncio.create_task(func1(), name='task1'),
        # 自动加入到事件循环里
        asyncio.create_task(func1(), name='task2')
    ]
    print('结束')
    done, pending = await asyncio.wait(task_list, timeout=None)
    print(done)


asyncio.run(main())

在这里插入图片描述

案例3:

import asyncio


async def func(n):
    print(n)
    await asyncio.sleep(2)
    print(n)
    return f"func{n}"


task_list = [
    func(1),
    func(2)
]


done, pending = asyncio.run(asyncio.wait(task_list))
print(done)

在这里插入图片描述

和案例2相比,task_list中直接写的任务名称,没有通过create_task创建Task对象,这是因为create_task函数创建任务之后会自动添加到事件循环中,在该案例中定义task_list前还没有创建事件循环,但是通过asyncio.wait()可以将任务添加到asyncio.run()创建的事件循环中。

1.6 asyncio.Future对象

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

asyncio中的Future对象是一个更偏向底层的可等待对象,代表异步任务的最终结果。通常不会直接用到这个对象,而是直接使用Task对象来完成任务的创建和状态的追踪。

Task继承Future,Task对象内部await结果是基于Future对象来的。

案例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: asyncio.Future):
    await asyncio.sleep(2)
    fut.set_result('future对象')


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

1.7 异步和非异步模块混合使用

python还有一个concurrent.futures.Future对象,它和asyncio.Future是不一样的。concurrent.futures.Future对象不可以用await修饰,asyncio.Future对象可以用await修饰。

但是asyncio提供了一个方法asyncio.wrap_future()可以将concurrent.futures.Future对象转换为asyncio.Future。

案例: asyncio + 不支持异步的模块

import requests
import asyncio


async def download_img(url: str):
    print("start download img: ", url)
    loop = asyncio.get_event_loop()
    # requests模块默认不支持异步操作,所以就使用线程池来配合实现
    future = loop.run_in_executor(None, requests.get, url)
    resp = await future
    print("download finished!")
    file_name = url.rsplit('/')[-1]
    with open(file_name, mode='wb') as file_object:
        file_object.write(resp.content)

if __name__ == '__main__':
    url_list = [
        'https://img.zcool.cn/community/0129bb5b45b124a8012036bec77a49.jpg@2o.jpg',
        'http://img.mm4000.com/file/4/64/6509a8b31c.jpg',
        'https://i.hexuexiao.cn/up/40/38/45/f11715885e77246ef81819174d453840.jpg'
    ]
    tasks = [download_img(url) for url in url_list]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))

1.8 异步迭代器

  • 异步迭代器
    实现了__aiter__()和__anext__()方法的对象。__anext__必须返回一个awaitable对象。async for会处理异步迭代器的__anext__()方法所返回的可等待对象,直到其引发一个StopAsyncIteration异常。

  • 异步可迭代对象
    可在async for语句中被使用的对象。必须通过它的__aiter__()方法返回一个asynchronous iterator。

案例1:

import asyncio


class Reader(object):
    """
    自定义异步迭代器(同时也是异步可迭代对对象)
    """
    def __init__(self):
        self.count = 0

    async def readline(self):
        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:
            raise StopAsyncIteration
        return val


async def func():
    obj = Reader()
    async for item in obj:
        print(item)


asyncio.run(func())

async for要写在async函数里,不然会报错:SyntaxError: 'async for' outside async function

1.9 异步上下文管理器

异步上下文管理器就是对象通过定义__aenter__()和__aexit__()方法来对async with语句中的环境进行控制。

可以通过with open来理解,enter中打开文件,exit中关闭文件。

案例:

import asyncio


class AsyncContextManager:
    def __init__(self):
        self.conn = None

    async def do_something(self):
        # 异步操作数据库
        return "111"

    async def __aenter__(self):
        # 异步连接数据库
        self.conn = await asyncio.sleep(1)
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        # 异步关闭数据库连接
        await asyncio.sleep(1)


async def func():
    async with AsyncContextManager() as f:
        result = await f.do_something()
        print(result)

if __name__ == '__main__':
    asyncio.run(func())

1.10 uvloop

uvloop是asyncio的事件循环的替代方案。uvloop的事件循环效率高于默认asyncio的事件循环。

注: uvloop不支持window平台,安装会报错;ubuntu上测试是可以正常安装的。

pip install uvloop

在这里插入图片描述
注意:一个asgi->uvicorn内部使用的就是uvloop

案例:

import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


async def func1():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "func1"


async def main():
    print('开始')
    task_list = [
        # 自动加入到事件循环里
        asyncio.create_task(func1(), name='task1'),
        # 自动加入到事件循环里
        asyncio.create_task(func1(), name='task2')
    ]
    print('结束')
    done, pending = await asyncio.wait(task_list, timeout=None)
    print(done)


# 内部的事件循环自动会变为uvloop
asyncio.run(main())

2. 案例学习

2.1 异步redis

在使用python代码操作redis时,连接/操作/断开都是网络IO。
环境: aioredis 2.0.1

python3.8 -m pip install aioredis

案例:

import asyncio
import aioredis


async def main():
	# 网络IO操作:创建redis连接
    redis = aioredis.from_url("redis://192.168.146.128")
    
    # 网络IO操作,设置key-value
    await redis.set("name", "zhangsan")
    
	# 网络IO操作:从redis中获取值
    value = await redis.get("name")
    print(value)
	# 网络IO操作:关闭redis连接
    await redis.close()


if __name__ == "__main__":
    asyncio.run(main())

redis库中存放的数据:
在这里插入图片描述
从redis库中读取数据:
在这里插入图片描述

2.2 异步MySQL

环境: aiomysql 0.1.1

python3.8 -m pip install aiomysql

在这里插入图片描述
案例:

import asyncio
import aiomysql


async def execute():
    # 网络IO操作,连接MySQL

    conn = await aiomysql.connect(host='192.168.146.128', port=3306, user='root', password='12345678', 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.3 异步FastAPI

环境:

  • fastapi 0.88.0 pip install fastapi
  • uvicorn 0.20.0 pip install uvicorn

案例:

import asyncio
import uvicorn
import aioredis
from aioredis import Redis
from fastapi import FastAPI

app = FastAPI()
REDIS_POOL = aioredis.ConnectionPool.from_url("redis://192.168.146.128", max_connections=10)


@app.get('/')
def index():
    return {"msg": "hello"}


@app.get("/red")
async def red():
    print("请求来了")

    await asyncio.sleep(3)
    # 连接池获取一个连接
    redis = aioredis.Redis(connection_pool=REDIS_POOL)

    await redis.execute_command("set", "color", "red")
    result = await redis.execute_command("get", "color")
    print("raw value:", result)

    await redis.close()
    return result


if __name__ == "__main__":
    uvicorn.run("14_FastAPI异步:app", host="192.168.146.128", port=5000, log_level="info")

在这里插入图片描述

2.4 异步爬虫

环境:

  • aiohttp 3.8.3 pip install aiohttp

案例:

import aiohttp
import asyncio


async def fetch(session, url):
    print("发送请求:", url)
    async with session.get(url, verify_ssl=False) as resp:
        text = await resp.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]
        done, pending = await asyncio.wait(tasks)

if __name__ == "__main__":
    asyncio.run(main())

在这里插入图片描述

3. 参考资料:

  • BIlibili学习视频: BV1Ke411W71L (非常好的入门课程)
  • asyncio官方文档:https://docs.python.org/zh-cn/3.8/library/asyncio.html
  • 事件循环: https://docs.python.org/zh-cn/3.8/library/asyncio-eventloop.html
  • Task对象: https://docs.python.org/zh-cn/3.8/library/asyncio-task.html#awaitables
  • asyncio和线程、进程混用: https://docs.python.org/3.8/library/asyncio-eventloop.html#asyncio.loop.run_in_executor
  • aioredis官方文档:https://aioredis.readthedocs.io/en/latest/
  • aiomysql官方文档: https://aiomysql.readthedocs.io/en/latest/index.html
  • Ubuntu上安装MySQL: https://kalacloud.com/blog/ubuntu-install-mysql/#:~:text=%E5%A6%82%E4%BD%95%E5%9C%A8%20Ubuntu%20%E4%B8%8A%E5%AE%89%E8%A3%85%20MySQL%201%20%E7%AC%AC%E4%B8%80%E6%AD%A5%20-%20%E5%AE%89%E8%A3%85,MySQL%20%E6%98%AF%E4%B8%8D%E6%98%AF%E5%AE%8C%E5%85%A8%E5%AE%89%E8%A3%85%E6%88%90%E5%8A%9F%20%E8%B5%B0%E5%88%B0%E8%BF%99%E9%87%8C%EF%BC%8C%E6%88%91%E4%BB%AC%E5%8F%AF%E4%BB%A5%E7%94%A8%20service%20%E5%91%BD%E4%BB%A4%EF%BC%8C%E7%9C%8B%E4%B8%80%E4%B8%8B%20mysql%20%E8%BF%99%E4%B8%AA%E6%9C%8D%E5%8A%A1%E6%98%AF%E4%B8%8D%E6%98%AF%E6%AD%A3%E5%B8%B8%E5%9C%A8%E8%BF%90%E8%A1%8C%E3%80%82%20
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值