Day 2 - 编写Web App骨架

由于我们的Web App建立在asyncio的基础上,因此用aiohttp写一个基本的app.py

  1. import logging; logging.basicConfig(level=logging.INFO)
  2. import asyncio, os, json, time
  3. from datetime import datetime
  4. from aiohttp import web
  5. def index(request):
  6. return web.Response(body=b'<h1>Awesome</h1>')
  7. @asyncio.coroutine
  8. def init(loop):
  9. app = web.Application(loop=loop)
  10. app.router.add_route('GET', '/', index)
  11. srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 9000)
  12. logging.info('server started at http://127.0.0.1:9000...')
  13. return srv
  14. loop = asyncio.get_event_loop()
  15. loop.run_until_complete(init(loop))
  16. loop.run_forever()

运行python app.py,Web App将在9000端口监听HTTP请求,并且对首页/进行响应:

  1. $ python3 app.py
  2. INFO:root:server started at http://127.0.0.1:9000...

这里我们简单地返回一个Awesome字符串,在浏览器中可以看到效果:

awesome-home

这说明我们的Web App骨架已经搭好了,可以进一步往里面添加更多的东西。

参考源码

day-02

原文: https://wizardforcel.gitbooks.io/liaoxuefeng/content/py3/108.html