Python开发从入门到精通:异步编程进阶与asyncio高级应用
《Python开发从入门到精通》设计指南第二十七篇:异步编程进阶与asyncio高级应用
一、学习目标与重点
💡 学习目标:掌握Python异步编程的高级技巧,包括协程调度、任务管理、异步IO操作、并发控制等;学习asyncio库的高级应用;通过实战案例开发异步应用程序。
⚠️ 学习重点:协程调度、任务管理、异步IO操作、并发控制、asyncio高级应用、异步应用实战。
27.1 异步编程概述
27.1.1 什么是异步编程
异步编程是一种编程模型,通过非阻塞的方式处理IO操作,提高应用程序的并发性能。在异步编程中,任务可以在等待IO操作完成时继续执行其他任务,而不需要阻塞等待。
27.1.2 异步编程的优势
- 高性能:通过非阻塞的方式处理IO操作,提高应用程序的并发性能。
- 高并发:可以同时处理大量的IO操作,提高应用程序的吞吐量。
- 简单易用:使用协程和异步IO操作,代码可读性高。
27.2 asyncio库的高级应用
27.2.1 协程调度
import asyncio asyncdeftask1():print("Task 1 start")await asyncio.sleep(1)print("Task 1 end")asyncdeftask2():print("Task 2 start")await asyncio.sleep(2)print("Task 2 end")asyncdefmain():print("Main start")await asyncio.gather(task1(), task2())print("Main end")if __name__ =="__main__": asyncio.run(main())27.2.2 任务管理
import asyncio asyncdeftask1():print("Task 1 start")await asyncio.sleep(1)print("Task 1 end")asyncdeftask2():print("Task 2 start")await asyncio.sleep(2)print("Task 2 end")asyncdefmain():print("Main start") task1_obj = asyncio.create_task(task1()) task2_obj = asyncio.create_task(task2())await task1_obj await task2_obj print("Main end")if __name__ =="__main__": asyncio.run(main())27.2.3 异步IO操作
import asyncio import aiohttp 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)if __name__ =="__main__": asyncio.run(main())27.2.4 并发控制
import asyncio import aiohttp from asyncio import Semaphore asyncdeffetch(session, url, sem):asyncwith sem:asyncwith session.get(url)as response:returnawait response.text()asyncdefmain(): urls =["https://www.example.com"]*10 sem = Semaphore(3)asyncwith aiohttp.ClientSession()as session: tasks =[asyncio.create_task(fetch(session, url, sem))for url in urls] results =await asyncio.gather(*tasks)for result in results:print(len(result))if __name__ =="__main__": asyncio.run(main())27.3 实战案例:异步爬虫
27.3.1 需求分析
开发一个异步爬虫,支持以下功能:
- 异步爬取多个网页。
- 解析网页内容。
- 保存爬取结果。
- 并发控制。
27.3.2 代码实现
import asyncio import aiohttp from asyncio import Semaphore from bs4 import BeautifulSoup asyncdeffetch(session, url, sem):asyncwith sem:asyncwith session.get(url)as response:returnawait response.text()asyncdefparse(html): soup = BeautifulSoup(html,"html.parser") title = soup.find("title").text return title asyncdefsave_result(title, url):withopen("results.txt","a")as f: f.write(f"{title}\t{url}\n")asyncdefcrawl(url, session, sem):try: html =await fetch(session, url, sem) title =await parse(html)await save_result(title, url)print(f"Successfully crawled {url}")except Exception as e:print(f"Failed to crawl {url}: {e}")asyncdefmain(): urls =["https://www.example.com","https://www.google.com","https://www.github.com","https://www.python.org","https://www.djangoproject.com"] sem = Semaphore(3)asyncwith aiohttp.ClientSession()as session: tasks =[asyncio.create_task(crawl(url, session, sem))for url in urls]await asyncio.gather(*tasks)if __name__ =="__main__": asyncio.run(main())27.3.3 实施过程
- 安装依赖:aiohttp、beautifulsoup4。
- 实现异步爬取和解析网页内容。
- 实现保存爬取结果。
- 实现并发控制。
- 运行应用。
27.3.4 最终效果
通过异步爬虫,我们可以实现以下功能:
- 异步爬取多个网页。
- 解析网页内容。
- 保存爬取结果。
- 并发控制。
27.4 实战案例:异步Web服务器
27.4.1 需求分析
开发一个异步Web服务器,支持以下功能:
- 处理HTTP请求。
- 异步读取文件。
- 异步数据库操作。
- 并发控制。
27.4.2 代码实现
import asyncio from aiohttp import web import aiofiles import sqlite3 from asyncio import Semaphore asyncdefread_file(file_path):asyncwith aiofiles.open(file_path,"r")as f:returnawait f.read()asyncdefget_data_from_db(): conn = sqlite3.connect("test.db") cursor = conn.cursor() cursor.execute("SELECT * FROM users") data = cursor.fetchall() conn.close()return data asyncdefindex(request): content =await read_file("index.html")return web.Response(text=content, content_type="text/html")asyncdefusers(request): sem = Semaphore(3)asyncwith sem: data =await get_data_from_db()return web.json_response(data)asyncdefcreate_app(): app = web.Application() app.add_routes([ web.get("/", index), web.get("/users", users)])return app if __name__ =="__main__": asyncio.run(web.run_app(create_app(), host="0.0.0.0", port=8000))27.4.3 实施过程
- 安装依赖:aiohttp、aiofiles。
- 实现异步读取文件和数据库操作。
- 实现HTTP请求处理。
- 实现并发控制。
- 运行应用。
27.4.4 最终效果
通过异步Web服务器,我们可以实现以下功能:
- 处理HTTP请求。
- 异步读取文件。
- 异步数据库操作。
- 并发控制。
总结
✅ 本文详细介绍了Python异步编程的高级技巧,包括协程调度、任务管理、异步IO操作、并发控制等;学习了asyncio库的高级应用;通过实战案例开发了异步爬虫和异步Web服务器。
✅ 建议读者在学习过程中多练习,通过编写代码加深对知识点的理解。