暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

【Python学习笔记】92、aiohttp

快易开发学习笔记 2020-10-21
374

asyncio
可以实现单线程并发IO操作。如果把asyncio
用在服务器端,可以用单线程+coroutine
实现多用户的高并发支持。

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

安装aiohttp

pip install aiohttp

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

  • /
     - 首页返回b'<h1>Hello Index</h1>'

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

代码如下:

import asyncio
from aiohttp import web
async def index(request):
await asyncio.sleep(0.5)
return web.Response(body=b'<h1>Hello Index</h1>')


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


async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', index)
app.router.add_route('GET', '/hello/{name}', hello)
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()

注意aiohttp
的初始化函数init()
也是一个coroutine
loop.create_server()
则利用asyncio
创建TCP服务。

文章转载自快易开发学习笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论