Aiohttp用于asyncio和 Python 的异步 HTTP 客户端/服务器。
主要特点
客户端代码:
import aiohttp import asyncio
async def main():
async with aiohttp.ClientSession() as session: async with session.get('http://python.org') as response:
print("Status:", response.status) print("Content-type:", response.headers['content-type'])
html = await response.text() print("Body:", html[:15], "...")
loop = asyncio.get_event_loop() loop.run_until_complete(main())
|
服务器示例:
from aiohttp import web
async def handle(request): name = request.match_info.get('name', "Anonymous") text = "Hello, " + name return web.Response(text=text)
app = web.Application() app.add_routes([web.get('/', handle), web.get('/{name}', handle)])
if <strong>name</strong> == '<strong>main</strong>': web.run_app(app)
|
有人将其与其他Python异步库比较,发现其是最快的:
- 第一代是可靠的老requests
- 第二代是使用线程发出请求的方法。为每个请求分拆一个本机线程,让它们在幕后运行。
- 第三代使用aiohttp
- 第四代使用HTTPX,它是 Python Web 客户端的现代实现。
- 使用pycurl
结果令人印象深刻,但 aiohttp 库仍然更快。