阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

使用aiohttp

26次阅读
没有评论

共计 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,访问首页:

使用 aiohttp

访问http://localhost:8080/Bob

使用 aiohttp

使用 aiohttp 时,定义处理不同 URL 的 async 函数,然后通过 app.add_routes() 添加映射,最后通过 run_app() 以 asyncio 的机制启动整个处理流程。

参考源码

app.py

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-08-07发表,共计815字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中