# 這是學習廖雪峯老師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()