Python开发从入门到精通:异步编程与协程

Python开发从入门到精通:异步编程与协程

《Python开发从入门到精通》设计指南第二十一篇:异步编程与协程

在这里插入图片描述

一、学习目标与重点

💡 学习目标:掌握Python异步编程的基本概念和方法,包括协程、任务调度、事件循环等;学习asyncio、aiohttp等核心库的使用;通过实战案例开发异步应用程序。
⚠️ 学习重点:协程的定义与使用、任务调度、事件循环、asyncio库、aiohttp库、异步编程实战。

21.1 异步编程概述

21.1.1 什么是异步编程

异步编程是一种并发编程方式,通过非阻塞的操作提高程序的执行效率。在异步编程中,程序可以在等待I/O操作完成时继续执行其他任务,而不需要阻塞等待。

21.1.2 异步编程的优势

  • 提高执行效率:在等待I/O操作完成时,程序可以继续执行其他任务。
  • 降低资源消耗:减少了线程切换的开销。
  • 简化代码结构:通过协程和任务调度,代码结构更加简洁。

21.1.3 异步编程的应用场景

  • 网络通信:如HTTP请求、Web服务器、WebSocket通信等。
  • 文件操作:如大文件的读取和写入。
  • 数据库操作:如异步数据库查询。

21.2 协程的定义与使用

21.2.1 协程的定义

协程(Coroutine)是一种轻量级的线程,可以在程序中进行暂停和恢复。在Python中,协程可以通过async def关键字定义。

21.2.2 协程的使用

import asyncio # 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(1)print('Hello again!')# 运行协程 asyncio.run(hello())

21.2.3 协程的暂停与恢复

import asyncio # 定义协程asyncdefcount():print('Counting...')await asyncio.sleep(1)print('Counted!')# 运行多个协程asyncdefmain():await asyncio.gather(count(), count(), count()) asyncio.run(main())

21.3 任务调度

21.3.1 创建任务

import asyncio # 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(1)print('Hello again!')# 创建任务asyncdefmain(): task1 = asyncio.create_task(hello()) task2 = asyncio.create_task(hello())await task1 await task2 asyncio.run(main())

21.3.2 任务的取消

import asyncio # 定义协程asyncdefhello():try:print('Hello, World!')await asyncio.sleep(1)print('Hello again!')except asyncio.CancelledError:print('Task cancelled!')# 创建任务并取消asyncdefmain(): task = asyncio.create_task(hello())await asyncio.sleep(0.5) task.cancel()try:await task except asyncio.CancelledError:print('Main: Task cancelled!') asyncio.run(main())

21.3.3 任务的超时

import asyncio # 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(2)print('Hello again!')# 任务超时asyncdefmain():try:await asyncio.wait_for(hello(), timeout=1)except asyncio.TimeoutError:print('Task timed out!') asyncio.run(main())

21.4 事件循环

21.4.1 事件循环的概述

事件循环是异步编程的核心组件,负责调度任务的执行。事件循环会不断地从任务队列中取出任务并执行,直到任务队列为空。

21.4.2 获取事件循环

import asyncio # 获取事件循环 loop = asyncio.get_event_loop()# 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(1)print('Hello again!')# 运行协程 loop.run_until_complete(hello())

21.4.3 事件循环的运行

import asyncio # 获取事件循环 loop = asyncio.get_event_loop()# 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(1)print('Hello again!')# 运行多个协程 loop.run_until_complete(asyncio.gather(hello(), hello(), hello()))

21.5 asyncio库

21.5.1 asyncio的基本用法

import asyncio # 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(1)print('Hello again!')# 运行协程 asyncio.run(hello())

21.5.2 asyncio的常用函数

  • asyncio.run():运行协程。
  • asyncio.create_task():创建任务。
  • asyncio.gather():收集多个协程的结果。
  • asyncio.wait_for():等待协程完成,设置超时。
  • asyncio.sleep():暂停协程。

21.5.3 asyncio的高级用法

import asyncio # 定义协程asyncdefhello():print('Hello, World!')await asyncio.sleep(1)print('Hello again!')# 使用Future对象asyncdefmain(): future = asyncio.Future() task = asyncio.create_task(hello()) task.add_done_callback(lambda t: future.set_result(t.result()))await future asyncio.run(main())

21.6 aiohttp库

21.6.1 安装aiohttp

pip install aiohttp 

21.6.2 发送HTTP请求

import aiohttp import asyncio # 发送GET请求asyncdeffetch(session, url):asyncwith session.get(url)as response:returnawait response.text()asyncdefmain():asyncwith aiohttp.ClientSession()as session: html =await fetch(session,'https://www.example.com')print(html) asyncio.run(main())

21.6.3 发送POST请求

import aiohttp import asyncio import json # 发送POST请求asyncdefpost_data(session, url, data):asyncwith session.post(url, data=data)as response:returnawait response.text()asyncdefmain():asyncwith aiohttp.ClientSession()as session: data ={'name':'张三','age':25} response =await post_data(session,'https://httpbin.org/post', data)print(response) asyncio.run(main())

21.6.4 发送JSON请求

import aiohttp import asyncio import json # 发送JSON请求asyncdefpost_json(session, url, data):asyncwith session.post(url, json=data)as response:returnawait response.text()asyncdefmain():asyncwith aiohttp.ClientSession()as session: data ={'name':'张三','age':25} response =await post_json(session,'https://httpbin.org/post', data)print(response) asyncio.run(main())

21.7 实战案例:异步HTTP客户端

21.7.1 需求分析

开发一个异步HTTP客户端,支持以下功能:

  • 发送HTTP请求。
  • 并发发送多个HTTP请求。
  • 处理响应数据。

21.7.2 代码实现

import aiohttp import asyncio import time # 发送HTTP请求asyncdeffetch(session, url): start_time = time.time()asyncwith session.get(url)as response: text =await response.text() elapsed_time = time.time()- start_time return url,len(text), elapsed_time # 并发发送HTTP请求asyncdefmain(): urls =['https://www.example.com','https://www.google.com','https://www.github.com','https://www.python.org','https://www.djangoproject.com']asyncwith aiohttp.ClientSession()as session: tasks =[asyncio.create_task(fetch(session, url))for url in urls] results =await asyncio.gather(*tasks)for url, length, elapsed_time in results:print(f'URL: {url}, 响应长度: {length}, 耗时: {elapsed_time:.2f}秒')# 运行程序if __name__ =='__main__': start_time = time.time() asyncio.run(main()) elapsed_time = time.time()- start_time print(f'总耗时: {elapsed_time:.2f}秒')

21.7.3 实施过程

  1. 安装aiohttp库。
  2. 定义发送HTTP请求的协程函数。
  3. 定义并发发送HTTP请求的协程函数。
  4. 运行程序。

21.7.4 最终效果

通过异步HTTP客户端,我们可以实现以下功能:

  • 发送HTTP请求。
  • 并发发送多个HTTP请求。
  • 处理响应数据。

21.8 实战案例:异步Web服务器

21.8.1 需求分析

开发一个异步Web服务器,支持以下功能:

  • 处理HTTP请求。
  • 提供静态文件服务。
  • 实现简单的API接口。

21.8.2 代码实现

from aiohttp import web import asyncio # 处理根路径请求asyncdefhandle_root(request):return web.Response(text='Hello, World!')# 处理API接口请求asyncdefhandle_api(request): data ={'name':'张三','age':25}return web.json_response(data)# 提供静态文件服务asyncdefhandle_static(request):return web.FileResponse('static/index.html')# 创建Web应用asyncdefcreate_app(): app = web.Application()# 添加路由 app.add_routes([ web.get('/', handle_root), web.get('/api', handle_api), web.get('/static/{name}', handle_static)])return app # 运行Web服务器if __name__ =='__main__': asyncio.run(web.run_app(create_app(), host='localhost', port=8080))

21.8.3 实施过程

  1. 安装aiohttp库。
  2. 定义处理HTTP请求的协程函数。
  3. 创建Web应用。
  4. 添加路由。
  5. 运行Web服务器。

21.8.4 最终效果

通过异步Web服务器,我们可以实现以下功能:

  • 处理HTTP请求。
  • 提供静态文件服务。
  • 实现简单的API接口。

总结

✅ 本文详细介绍了Python异步编程的基本概念和方法,包括协程、任务调度、事件循环等;学习了asyncio、aiohttp等核心库的使用;通过实战案例开发了异步HTTP客户端和异步Web服务器。
✅ 建议读者在学习过程中多练习,通过编写代码加深对知识点的理解。

Read more

RabbitMQ如何成为分布式系统的“神经中枢“?——从安装部署到C++调用实战的完整流程,带你体验它的奥妙所在!​

RabbitMQ如何成为分布式系统的“神经中枢“?——从安装部署到C++调用实战的完整流程,带你体验它的奥妙所在!​

文章目录 * 本篇摘要 * ①·RabbitMq(轻量级消息队列中间件) 介绍 * RabbitMQ 是什么? * 核心功能与特点 * 1. **核心功能** * 2. **核心优势** * RabbitMQ 的核心概念 * 1. **生产者(Producer)** * 2. **消费者(Consumer)** * 3. **队列(Queue)** * 4. **交换机(Exchange)** * 5. **绑定(Binding)** * 工作流程(以 Direct 交换机为例) * 常见应用场景 * RabbitMQ 与相关技术对比 * 图像理解 * 总结一句话 * ②·RabbitMq 安装教程 * RabbitMq安装 * **1. 安装 RabbitMQ** * **2. 启动 & 检查状态** * **3. 创建管理员用户(

By Ne0inhk
SkyWalking - Kafka _ RabbitMQ 消息链路追踪支持

SkyWalking - Kafka _ RabbitMQ 消息链路追踪支持

👋 大家好,欢迎来到我的技术博客! 📚 在这里,我会分享学习笔记、实战经验与技术思考,力求用简单的方式讲清楚复杂的问题。 🎯 本文将围绕SkyWalking这个话题展开,希望能为你带来一些启发或实用的参考。 🌱 无论你是刚入门的新手,还是正在进阶的开发者,希望你都能有所收获! 文章目录 * SkyWalking - Kafka / RabbitMQ 消息链路追踪支持 🚀 * 为什么需要消息链路追踪?🤔 * SkyWalking 核心概念回顾 🔍 * Kafka 链路追踪支持 🐘 * 1. 自动探针(推荐)✅ * 前提条件 * 工作原理 * Java 代码示例(无需修改业务代码!) * 验证追踪效果 * 2. 手动埋点(高级场景)🛠️ * 添加依赖 * 手动注入上下文(Producer) * 手动提取上下文(Consumer) * RabbitMQ 链路追踪支持 🐇 * 工作原理 * Java 代码

By Ne0inhk
KWDB 运维实战:拒绝数据孤岛!用 SQL 打通 Metrics 与 CMDB 的“任督二脉”

KWDB 运维实战:拒绝数据孤岛!用 SQL 打通 Metrics 与 CMDB 的“任督二脉”

在互联网大厂,服务器监控(AIOps)是基础设施的命脉。一旦核心数据库或网关宕机,每分钟的损失可能高达数百万。 传统的监控方案(如 Zabbix、Prometheus)在面对海量指标时各有痛点:Zabbix 擅长告警但历史数据存储能力弱;Prometheus 查询语言(PromQL)学习曲线陡峭且不易与业务数据(如 CMDB)进行关联分析。 运维人员真正需要的是:既能像 Prometheus 一样吞吐海量时序数据,又能像 MySQL 一样用标准 SQL 进行复杂关联查询。 本文将带你体验如何用 KWDB 3.1.0 搭建一个轻量级但高性能的 服务器监控系统,用一个数据库搞定“指标存储”与“资产管理”。 * 场景设定: 监控 500 台服务器的 CPU、内存、磁盘 IO 和网络流量。 * 核心挑战:

By Ne0inhk
直击复杂 SQL 瓶颈:基于代价的连接条件下推技术落地

直击复杂 SQL 瓶颈:基于代价的连接条件下推技术落地

一、引言 在数据库理论的学习过程中,我们常常接触到简洁优美的SQL示例——单表查询、简单连接、基础过滤,这些案例清晰地展示了关系代数的基本原理。然而,当我们步入真实的业务系统,面对的SQL语句往往如同缠绕的线团:公用表表达式(CTE)层层嵌套,子查询彼此交织,窗口函数与聚集计算随处可见。 这种复杂性并非开发人员的炫技,而是业务逻辑的自然映射。遗憾的是,这种为提升可读性而组织的SQL结构,却给查询优化器带来了严峻考验。在众多性能瓶颈中,有一个问题尤为突出:高选择性的连接条件无法穿透复杂的子查询结构,导致数据过滤发生在错误的时间点。本文将深入探讨这一问题的本质,并介绍一种基于代价模型的连接条件下推解决方案,展示如何让优化器既懂“安全”,又知“成本”。 二、性能困境:过滤迟到的代价 2.1 真实场景的切面分析 在大量客户业务系统中,一种常见的SQL编写模式反复出现:开发人员习惯先在子查询或CTE中完成复杂的预处理逻辑——去重、排序、窗口计算,然后再将这些预处理结果与其它表进行连接,最后施加过滤条件。从业务语义角度看,这种写法清晰自然;但从执行效率角度看,却暗藏危机。 考虑

By Ne0inhk