aio_web.py 815 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. __author__ = 'Michael Liao'
  4. '''
  5. async web application.
  6. '''
  7. import asyncio
  8. from aiohttp import web
  9. async def index(request):
  10. await asyncio.sleep(0.5)
  11. return web.Response(body=b'<h1>Index</h1>')
  12. async def hello(request):
  13. await asyncio.sleep(0.5)
  14. text = '<h1>hello, %s!</h1>' % request.match_info['name']
  15. return web.Response(body=text.encode('utf-8'))
  16. async def init(loop):
  17. app = web.Application(loop=loop)
  18. app.router.add_route('GET', '/', index)
  19. app.router.add_route('GET', '/hello/{name}', hello)
  20. srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
  21. print('Server started at http://127.0.0.1:8000...')
  22. return srv
  23. loop = asyncio.get_event_loop()
  24. loop.run_until_complete(init(loop))
  25. loop.run_forever()