# 这是学习廖雪峰老师python教程的学习笔记python
1、概览web
asyncio能够实现单线程并发IO操做。若是仅用在客户端,发挥的威力不大。若是把asyncio用在服务器端,例如Web服务器,因为HTTP链接就是IO操做,所以能够用单线程+coroutine实现多用户的高并发支持。服务器
asyncio实现了TCP、UDP、SSL等协议,aiohttp则是基于asyncio实现的HTTP框架并发
2、基于aiohttp编写HTTP服务器app
一、安装aiohttp框架
pip install aiohttpasync
二、处理的URLide
/ - 首页返回b'<h1>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>Index</h1>')
async def hello(request): #处理/hello/{name}
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) #指定URL对应的函数
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()