阅读目录:html
1.开始编写web
因为咱们的Web App创建在 asyncio 的基础上,所以用 aiohttp 写一个基本的 app.py ,如下是廖雪峰老师教程中的代码,可是存在不少问题,json
在web.Response(body=b’<h1>Awesome</h1>’) 中未设置转码和头信息,致使最终点击 http://127.0.0.1:9000 是一个二进制的文件下载;
app.make_handler() 这种方式已经太过于老旧,运行会报警告;
在aiohttp中使用yield from方式太过于老旧,若是实在要用下面代码方式的话建议改成 async 和await。
感兴趣的同窗能够看看app
廖雪峰老师教程中的代码:async
import logging; logging.basicConfig(level=logging.INFO) import asyncio, os, json, time from datetime import datetime from aiohttp import web def index(request): return web.Response(body=b'<h1>Awesome</h1>') @asyncio.coroutine def init(loop): app = web.Application(loop=loop) app.router.add_route('GET', '/', index) srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 9000) logging.info('server started at http://127.0.0.1:9000...') return srv loop = asyncio.get_event_loop() loop.run_until_complete(init(loop)) loop.run_forever()
我的:oop
import logging
from aiohttp import web
logging.basicConfig(level=logging.INFO) #配置logging的基本信息,level=logging.INFO,记录INFO及以上的日志
def index(request):
return web.Response(body='<h1>Awesome</h1>'.encode('utf-8'),content_type='text/html')
def init():
app = web.Application()
app.router.add_route('GET','/', index)
web.run_app(app,host='127.0.0.1',port=8000)
logging.info('server started at http://127.0.0.1:9001....')
init()
这说明咱们的Web App骨架已经搭好了,能够进一步往里面添加更多的东西。spa