aiohttp,一个异步请求的 Python 库!
介绍:
aiohttp 是基于Python asyncio构建的异步HTTP客户端和服务器框架,能够同时处理数千个并发连接而不会阻塞主线程。与传统的同步请求库(如requests)相比,aiohttp在需要发起大量HTTP请求的场景下性能优势明显。该库同时支持客户端和服务器端功能,既可以用于爬虫、API调用等客户端场景,也可以构建高性能的异步Web服务。
核心特性:
- 完全异步:基于asyncio,支持高并发非阻塞IO操作
- 客户端与服务器:同时提供HTTP客户端和Web服务器功能
- WebSocket支持:原生支持WebSocket双向通信
- 中间件机制:灵活的中间件系统,便于扩展功能
- 会话管理:高效的连接池和会话复用机制
- 流式传输:支持大文件的流式上传和下载
安装
pip install aiohttp
一、基本功能
1、异步HTTP GET请求
异步请求是aiohttp的核心功能,能够并发执行多个HTTP请求而不相互阻塞。下面的代码展示如何使用aiohttp发起异步GET请求,通过async/await语法实现非阻塞调用。ClientSession对象管理连接池,能够复用TCP连接提高效率。
import aiohttp
import asyncio
# 修复 Windows 的 asyncio 兼容问题
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
print(f"状态码: {response.status}")
data = await response.text()
return data
# 运行异步任务
async def main():
url = 'https://www.baidu.com/'
result = await fetch_data(url)
print(f"响应内容长度: {len(result)}")
asyncio.run(main())
2、并发多个请求
aiohttp在于并发处理多个请求。下面的代码演示如何使用asyncio.gather同时发起多个HTTP请求,所有请求并行执行。
import aiohttp
import asyncio
# 修复 Windows 的 asyncio 兼容问题
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def fetch_multiple(urls):
async with aiohttp.ClientSession() as session:
tasks = []
for url in urls:
task = asyncio.create_task(session.get(url))
tasks.append(task)
responses = await asyncio.gather(*tasks)
results = []
for response in responses:
data = await response.text()
results.append(data)
return results
# 并发请求多个URL
async def main():
urls = [
'https://api.github.com',
'https://httpbin.org/get',
'https://jsonplaceholder.typicode.com/posts/1'
]
results = await fetch_multiple(urls)
print(f"成功获取 {len(results)} 个响应")
asyncio.run(main())
3、POST请求与JSON数据
在实际应用中,经常需要向服务器提交数据。下面的代码展示如何使用aiohttp发送POST请求,包括JSON数据的提交和响应的解析。通过json参数可以自动序列化Python字典为JSON格式,response.json()方法则将响应反序列化为Python对象。
import aiohttp
import asyncio
# 修复 Windows 的 asyncio 兼容问题
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def post_data():
async with aiohttp.ClientSession() as session:
url = 'https://httpbin.org/post'
data = {
'username': 'testuser',
'email': 'test@example.com'
}
async with session.post(url, json=data) as response:
result = await response.json()
print(f"服务器响应: {result['json']}")
asyncio.run(post_data())
二、高级功能
1、构建异步Web服务器
aiohttp不仅是客户端工具,还能构建高性能的异步Web服务器。下面的代码展示如何创建一个简单的Web应用,定义路由和处理函数。通过装饰器或路由表配置URL映射,处理函数使用async def定义以支持异步操作。
from aiohttp import web
import asyncio
# 修复 Windows 的 asyncio 兼容问题
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def handle_index(request):
return web.Response(text="访问首页")
async def handle_api(request):
data = {'message': 'API响应', 'status': 'success'}
return web.json_response(data)
# 创建应用和路由
app = web.Application()
app.router.add_get('/', handle_index)
app.router.add_get('/api', handle_api)
# 启动服务器
if __name__ == '__main__':
web.run_app(app, host='127.0.0.1', port=8080)
2、请求超时与错误处理
在生产环境中,必须处理网络异常和超时情况。下面的代码展示如何设置请求超时和捕获各种异常。通过aiohttp.ClientTimeout可以精细控制连接、读取等各阶段的超时时间。
import aiohttp
import asyncio
# 修复 Windows 的 asyncio 兼容问题
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def fetch_with_timeout():
timeout = aiohttp.ClientTimeout(total=10, connect=3)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
async with session.get('https://httpbin.org/delay/2') as response:
data = await response.text()
print("请求成功")
except asyncio.TimeoutError:
print("请求超时")
except aiohttp.ClientError as e:
print(f"请求错误: {e}")
asyncio.run(fetch_with_timeout())
3、WebSocket实时通信
import aiohttp
import asyncio
# 修复 Windows 的 asyncio 兼容问题
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def websocket_example():
async with aiohttp.ClientSession() as session:
async with session.ws_connect('wss://echo.websocket.org') as ws:
# 发送消息
await ws.send_str('Hello WebSocket')
# 接收消息
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(f"收到消息: {msg.data}")
break
elif msg.type == aiohttp.WSMsgType.ERROR:
print("WebSocket错误")
break
asyncio.run(websocket_example())

浙公网安备 33010602011771号