百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

Python教程——20.协程 - 2

mhr18 2025-05-23 18:45 17 浏览 0 评论

异步编程

asyncio.Future 对象

Task 继承 Future, Task对象内部中的await结果的处理基于Future对象来的

在Future对象中会保存当前执行的这个协程任务的状态,如果当前任务状态为finished, 则await不再等待。


示例1:

import asyncio


async def main():
    # 获取当前事件循环
    loop = asyncio.get_running_loop()
    # 创建一个任务[Future对象] 当前没有任何任务
    fut = loop.create_future()
    # 等待任务的最终结果,没有结果则一直等待
    await fut


asyncio.run(main())


示例2:

import asyncio


async def set_after(fut):
    await asyncio.sleep(2)
    fut.set_result('这是一个测试结果')


async def main():
    # 获取事件循环
    loop = asyncio.get_running_loop()

    # 创建一个任务, 并且当前任务没有绑定任何行为, 则这个任务永远不知道什么时候结束
    fut = loop.create_future()

    # 手动设置future任务的最终结果
    await loop.create_task(set_after(fut))

    # 等待Future对象获取最终的结果, 否则就一直等
    data = await fut
    print(data)


asyncio.run(main())


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)


# 创建线程池
pool = ThreadPoolExecutor(max_workers=5)

# 创建进程池
# pool = ProcessPoolExecutor(max_workers=5)

for i in range(10):
    fut = pool.submit(func, i)
    print(fut)

一般情况下,代码编写需要统一编程风格,简而言之,就是如果使用的是线程/进程,则整个程序都统一使用线程/进程。

只有一种情况可能会进行交叉编程。一个项目中的所有IO请求为协程异步请求,假设MySQL数据库版本过低导致无法使用协程进行并发存储,这种情况会使用线程/进程完成并发存储任务。

import time
import asyncio
import concurrent.futures


def func_1():
    time.sleep(2)
    return '测试'


async def main():
    loop = asyncio.get_running_loop()

    # 在协程函数中运行普通函数 在执行函数时,协程内部会自动创建一个线程池来运行任务
    # run_in_executor()方法第一个参数为None时则默认创建一个线程池
    fut = loop.run_in_executor(None, func_1)
    result = await fut
    print('当前方式会自动创建一个线程池去执行普通函数: ', result)

    # 在协程函数中运行基于线程池的任务, 效果与以上代码一致
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, func_1)
        print('在线程池中得到的执行结果: ', result)

    # 在协程函数中运行基于进程池的任务
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, func_1)
        print('在进程池中得到的执行结果: ', result)


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


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

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 f:
        f.write(response.content)


if __name__ == '__main__':
    url_list = [
        'http://pic.bizhi360.com/bbpic/98/10798.jpg',
        'http://pic.bizhi360.com/bbpic/92/10792.jpg',
        'http://pic.bizhi360.com/bbpic/86/10386.jpg'
    ]
    
    tasks = [download_image(url) for url in url_list]
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(asyncio.wait(tasks))
    asyncio.run(asyncio.wait(tasks))


异步迭代器

什么是异步迭代器?

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


什么是异步可迭代对象?

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

import asyncio


# 自定义异步迭代器
class Reader:
    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:
            raise StopAsyncIteration
        return val


async def func():
    obj = Reader()
    # 异步for循环必须在协程函数内执行,协程函数名称随意取名
    async for item in obj:
        print(item)


asyncio.run(func())


异步上下文管理器

此种现象通过定义__aenter__()和__axeit__()方法来对async with语句中的环境进行控制。

import asyncio


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

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

    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)


asyncio.run(func())


uvloop

是asyncio的事件循环的替代方案。

uvloop事件循环的执行效率比asyncio默认的事件循环的效率高。

# pip install uvloop

import asyncio
import uvloop

# 设置事件循环为uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

# 编写的asyncio代码与之前一致

# 内部事件循环会自动切到uvloop
asyncio.run(...)


实战案例

异步操作 Redis

在使用python代码操作redis时,像连接、读取/写入、断开都是IO操作。

pip install aioredis==1.3.1

案例1:

import asyncio
import aioredis


async def execute(address):
    print('开始执行: ', address)
    # 网络IO 创建redis连接
    redis = await aioredis.create_redis(address)
    # 网络IO 在redis中设置哈希值
    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('结束...')


asyncio.run(execute('redis://127.0.0.1:6379/0'))


案例2:

import asyncio
import aioredis


async def execute(address, password):
    print('开始执行: ', address)
    # 网络IO 创建redis连接
    redis = await aioredis.create_redis_pool(address, password=password)
    # 网络IO 在redis中设置哈希值
    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('结束...')

task_list = [
    execute('redis://localhost:6379/0', None),
    execute('redis://localhost:6379/1', None)
]


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='root', db='mysql')

    # 网络IO操作 创建游标
    cursor = await conn.cursor()

    # 网络IO操作 执行sql
    await cursor.execute('select host,user from user')

    # 网络IO操作 获取sql结果
    result = await cursor.fetchall()
    print(result)

    # 网络IO操作
    await cursor.close()
    conn.close()


asyncio.run(execute())


案例2:

import asyncio
import aiomysql


async def execute(host, password):
    print('开始连接:', host)
    # 网络IO操作 连接mysql
    conn = await aiomysql.connect(host=host, port=3306, user='root', password=password, db='mysql')

    # 网络IO操作 创建游标
    cursor = await conn.cursor()

    # 网络IO操作 执行sql
    await cursor.execute('select host,user from user')

    # 网络IO操作 获取sql结果
    result = await cursor.fetchall()
    print(result)

    # 网络IO操作
    await cursor.close()
    conn.close()
    print('结束:', host)


task_list = [
    execute('localhost', 'root'),
    execute('localhost', 'root')
]


asyncio.run(asyncio.wait(task_list))


FastAPI框架

pip install uvicorn
pip install fastapi


示例:

import uvicorn
import asyncio
import aioredis
from fastapi import FastAPI

app = FastAPI()

# 创建redis连接池
REDIS_POOL = aioredis.ConnectionsPool('redis://localhost: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 = aioredis.Redis(conn)

    # 设置值
    await redis.hmset_dict('car_fastApi', key1=1, key2=2, key3=3)

    # 读取值
    result = await redis.hgetall('car_fastApi', encoding='utf-8')
    print(result)

    # 将单个连接归还给连接池
    REDIS_POOL.release(conn)

    return result


if __name__ == '__main__':
    # fastapi_test为当前这个脚本文件的名称
    uvicorn.run("fastapi_test:app", host='127.0.0.1', port=5000, log_level='info')


爬虫

import asyncio
import aiohttp


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',
        ]

        tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
        await asyncio.wait(tasks)


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

相关推荐

Spring Boot 分布式事务实现简单得超乎想象

环境:SpringBoot2.7.18+Atomikos4.x+MySQL5.71.简介关于什么是分布式事务,本文不做介绍。有需要了解的自行查找相关的资料。本篇文章将基于SpringBoot...

Qt编写可视化大屏电子看板系统15-曲线面积图

##一、前言曲线面积图其实就是在曲线图上增加了颜色填充,单纯的曲线可能就只有线条以及数据点,面积图则需要从坐标轴的左下角和右下角联合曲线形成完整的封闭区域路径,然后对这个路径进行颜色填充,为了更美观...

Doris大数据AI可视化管理工具SelectDB Studio重磅发布!

一、初识SelectDBStudioSelectDBStudio是专为ApacheDoris湖仓一体典型场景实战及其兼容数据库量身打造的GUI工具,简化数据开发与管理。二、Select...

RAD Studio 、Delphi或C++Builder设计代码编译上线缩短开发时间

#春日生活打卡季#本月,Embarcadero宣布RADStudio12.3Athens以及Delphi12.3和C++Builder12.3,提供下载。RADStudio12.3A...

Mybatis Plus框架学习指南-第三节内容

自动填充字段基本概念MyBatis-Plus提供了一个便捷的自动填充功能,用于在插入或更新数据时自动填充某些字段,如创建时间、更新时间等。原理自动填充功能通过实现com.baomidou.myba...

「数据库」Sysbench 数据库压力测试工具

sysbench是一个开源的、模块化的、跨平台的多线程性能测试工具,可以用来进行CPU、内存、磁盘I/O、线程、数据库的性能测试。目前支持的数据库有MySQL、Oracle和PostgreSQL。以...

如何选择适合公司的ERP(选erp系统的经验之谈)

很多中小公司想搞ERP,但不得要领。上ERP的目的都是歪的,如提高效率,减少人员,堵住财务漏洞等等。真正用ERP的目的是借机提升企业管理能力,找出管理上的问题并解决,使企业管理更规范以及标准化。上ER...

Manus放开注册,但Flowith才是Agent领域真正的yyds

大家好,我是运营黑客。前天,AIAgent领域的当红炸子鸡—Manus宣布全面放开注册,终于,不需要邀请码就能体验了。于是,赶紧找了个小号去确认一下。然后,额……就被墙在了外面。官方解释:中文版...

歌浓酒庄总酿酒师:我们有最好的葡萄园和最棒的酿酒师

中新网1月23日电1月18日,张裕董事长周洪江及总经理孙健一行在澳大利亚阿德莱德,完成了歌浓酒庄股权交割签约仪式,这也意味着张裕全球布局基本成型。歌浓:澳大利亚年度最佳酒庄据悉,此次张裕收购的...

软件测试进阶之自动化测试——python+appium实例

扼要:1、了解python+appium进行APP的自动化测试实例;2、能根据实例进行实训操作;本课程主要讲述用python+appium对APP进行UI自动化测试的例子。appium支持Androi...

为什么说Python是最伟大的语言?看图就知道了

来源:麦叔编程作者:麦叔测试一下你的分析能力,直接上图,自己判断一下为什么Python是最好的语言?1.有图有真相Java之父-JamesGoshlingC++之父-BjarneStrou...

如何在Eclipse中配置Python开发环境?

Eclipse是著名的跨平台集成开发环境(IDE),最初主要用来Java语言开发。但是我们通过安装不同的插件Eclipse可以支持不同的计算机语言。比如说,我们可以通过安装PyDev插件,使Eclip...

联合国岗位上新啦(联合国的岗位)

联合国人权事务高级专员办事处PostingTitleIntern-HumanRightsDutyStationBANGKOKDeadlineOct7,2025CategoryandL...

一周安全漫谈丨工信部:拟定超1亿条一般数据泄露属后果严重情节

工信部:拟定超1亿条一般数据泄露属后果严重情节11月23日,工信部官网公布《工业和信息化领域数据安全行政处罚裁量指引(试行)(征求意见稿)》。《裁量指引》征求意见稿明确了行政处罚由违法行为发生地管辖、...

oracle列转行以及C#执行语句时报错问题

oracle列转行的关键字:UNPIVOT,经常查到的怎么样转一列,多列怎么转呢,直接上代码(sshwomeyourcode):SELECTsee_no,diag_no,diag_code,...

取消回复欢迎 发表评论: