359025439 发表于 2018-8-10 06:10:38

Python学习笔记__20.4章 aiohttp

  # 这是学习廖雪峰老师python教程的学习笔记
  1、概览
  asyncio可以实现单线程并发IO操作。如果仅用在客户端,发挥的威力不大。如果把asyncio用在服务器端,例如Web服务器,由于HTTP连接就是IO操作,因此可以用单线程+coroutine实现多用户的高并发支持。
  asyncio实现了TCP、UDP、SSL等协议,aiohttp则是基于asyncio实现的HTTP框架
  2、基于aiohttp编写HTTP服务器
  1、安装aiohttp
  pip install aiohttp
  2、处理的URL

[*]  / -      首页返回b'<h1>Index</h1>';
[*]  /hello/{name} - 根据URL参数返回文本hello, %s!
  3、代码
  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()
页: [1]
查看完整版本: Python学习笔记__20.4章 aiohttp