aiohttp

asyncio能够实现单线程并发IO操做。若是仅用在客户端,发挥的威力不大。若是把asyncio用在服务器端,例如Web服务器,因为HTTP链接就是IO操做,所以能够用单线程+coroutine实现多用户的高并发支持。python

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

咱们先安装aiohttp服务器

pip install aiohttp

而后编写一个HTTP服务器,分别处理如下URL:并发

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

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

代码以下:async

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): 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()也是一个coroutineloop.create_server()则利用asyncio建立TCP服务。函数

相关文章
相关标签/搜索