概述
用于asyncio和Python的异步HTTP客户端/服务器。当前版本是3.6.2。
- 关键特性
支持HTTP客户端和服务器。
支持WebSocket的客户端和服务器,而没有回调地狱。
Web服务器具有中间件,信号和可插入路由。
安装
pip install aiohttp
您可能需要安装可选的cchardet库,以快速替换chardet:
pip install cchardet
为了通过客户端API加快DNS解析速度,您也可以安装aiodns。强烈建议使用此选项:
pip install aiodns
一键式安装所有
pip install aiohttp[speedups]
开始
客户端
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
if __name__ == '__main__':
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 __name__ == '__main__':
web.run_app(app)