- 支持 HTTP 协议的客户端和服务器端。
- 开箱即用地支持 HTTP 客户端和服务器 WebSockets,并避免了回调地狱。
- 提供带有中间件和可插拔路由的 Web 服务器。
从网上获取一些内容:
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print("状态:", response.status)
print("内容类型:", response.headers['content-type'])
html = await response.text()
print("正文:", html[:15], "...")
asyncio.run(main())输出:
状态:200 内容类型:text/html; charset=utf-8 正文:<!doctype html> ...
来自 requests ?阅读 我们为什么需要这么多行。
一个简单的服务器示例:
# examples/server_simple.py
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "你好," + name
return web.Response(text=text)
async def wshandle(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
async for msg in ws:
if msg.type == web.WSMsgType.text:
await ws.send_str("你好,{}".format(msg.data))
elif msg.type == web.WSMsgType.binary:
await ws.send_bytes(msg.data)
elif msg.type == web.WSMsgType.close:
break
return ws
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/echo', wshandle),
web.get('/{name}', handle)])
if __name__ == '__main__':
web.run_app(app)https://aiohttp.readthedocs.io/
https://github.com/aio-libs/aiohttp-demos
欢迎提出 Pull Request 以将您的链接添加到这些页面!
aio-libs 讨论: https://github.com/aio-libs/aiohttp/discussions
Matrix: #aio-libs:matrix.org
我们支持 Stack Overflow。 请在您的问题中添加 aiohttp 标签。
您还可以选择安装 aiodns 库(强烈推荐以提高速度)。
aiohttp 在 Apache 2 许可证下提供。
aiohttp 社区感谢 Keepsafe (https://www.getkeepsafe.com) 在项目早期提供的支持。
最新的开发版本可在 GitHub 仓库中获得: https://github.com/aio-libs/aiohttp
如果您对效率感兴趣,AsyncIO 社区在官方 wiki 上维护了一份基准测试列表: https://github.com/python/asyncio/wiki/Benchmarks