共计 815 个字符,预计需要花费 3 分钟才能阅读完成。
asyncio可以实现单线程并发 IO 操作。如果仅用在客户端,发挥的威力不大。如果把 asyncio 用在服务器端,例如 Web 服务器,由于 HTTP 连接就是 IO 操作,因此可以用单线程 +async函数实现多用户的高并发支持。
asyncio实现了 TCP、UDP、SSL 等协议,aiohttp则是基于 asyncio 实现的 HTTP 框架。
我们先安装aiohttp:
$ pip install aiohttp
然后编写一个 HTTP 服务器,分别处理以下 URL:
/– 首页返回Index Page;/{name}– 根据 URL 参数返回文本Hello, {name}!。
代码如下:
# app.py
from aiohttp import web
async def index(request):
text = "<h1>Index Page</h1>"
return web.Response(text=text, content_type="text/html")
async def hello(request):
name = request.match_info.get("name", "World")
text = f"<h1>Hello, {name}</h1>"
return web.Response(text=text, content_type="text/html")
app = web.Application()
# 添加路由:
app.add_routes([web.get("/", index), web.get("/{name}", hello)])
if __name__ == "__main__":
web.run_app(app)
直接运行app.py,访问首页:

访问http://localhost:8080/Bob:

使用 aiohttp 时,定义处理不同 URL 的 async 函数,然后通过 app.add_routes() 添加映射,最后通过 run_app() 以 asyncio 的机制启动整个处理流程。
参考源码
app.py
正文完
星哥玩云-微信公众号






