1. aiohttp
    2. 阅读: 67673
    3. asyncio可以实现单线程并发IO操作。如果仅用在客户端,发挥的威力不大。如果把asyncio用在服务器端,例如Web服务器,由于HTTP连接就是IO操作,因此可以用单线程+coroutine实现多用户的高并发支持。
    4. asyncio实现了TCPUDPSSL等协议,aiohttp则是基于asyncio实现的HTTP框架。
    5. 我们先安装aiohttp
    6. pip install aiohttp
    7. 然后编写一个HTTP服务器,分别处理以下URL
    8. / - 首页返回b'<h1>Index</h1>'
    9. /hello/{name} - 根据URL参数返回文本hello, %s!。
    10. 代码如下:
    11. import asyncio
    12. from aiohttp import web
    13. async def index(request):
    14. await asyncio.sleep(0.5)
    15. return web.Response(body=b'<h1>Index</h1>')
    16. async def hello(request):
    17. await asyncio.sleep(0.5)
    18. text = '<h1>hello, %s!</h1>' % request.match_info['name']
    19. return web.Response(body=text.encode('utf-8'))
    20. async def init(loop):
    21. app = web.Application(loop=loop)
    22. app.router.add_route('GET', '/', index)
    23. app.router.add_route('GET', '/hello/{name}', hello)
    24. srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
    25. print('Server started at http://127.0.0.1:8000...')
    26. return srv
    27. loop = asyncio.get_event_loop()
    28. loop.run_until_complete(init(loop))
    29. loop.run_forever()
    30. 注意aiohttp的初始化函数init()也是一个coroutineloop.create_server()则利用asyncio创建TCP服务。
    31. 参考源码
    32. aio_web.py