aiohttp

本文介绍如何利用Python的AsyncIO模块及Aiohttp框架建立一个支持高并发的HTTP服务器,并通过示例代码展示了处理不同URL请求的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

asyncio可实现单线程并发IO操作。如果把asyncio用在服务器端,例如web服务器,由于HTTP连接就是IO操作,因此可以用单线程+协程实现多用户的高并发支持。

 

asyncio实现了TCP,UDP,SSL等协议,aiohttp则是基于asyncio实现的HTTP框架。

编写一个HTTP服务器,分别处理以下URL:

   /  首页返回b'<h1>Index</h1>'

   /hello/{name} 根据url参数返回文本hello,%s!

代码如下:

 

import asyncio
from aiohttp import web

async def index(request):
    await asyncio.sleep(1)
    return web.Response(body=b'<h1>Index</h1>',content_type='text/html')

async def hello(request):
    await  asyncio.sleep(1)
    text = '<h1>hello, %s!</h1>' % request.match_info['name']
    return web.Response(body=text.encode('utf-8'),content_type='text/html')

async def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET','/',index)
    app.router.add_route('GET','/hello/{name}',hello)
    #创建一个TCP服务
    srv = await loop.create_server(app.make_handler(),'127.0.0.1',8000)
    print('Server started at http://127.0.0.1:8000...')
    return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()

 

转载于:https://www.cnblogs.com/1zhangwenjing/p/7749463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值