我们继续学习Python异步编程,这里将介绍异步Web框架sanic,为什么不是tornado?从框架的易用性来说,Flask要远远比tornado简单,可惜flask不支持异步,而sanic就是类似Flask语法的异步框架。
不过sanic对环境有要求:
macOS/linux
python 3.6+
不过,我在macOS上安装 sanic 还是踩了坑。依赖库ujson一直安装失败。最后不得不卸载官方python,安装 miniconda(第三方Python安装包,集成了一些额外的工具)。
安装 sanic
> pip3 install sanic
sanic 开发第一个例子
编写官方的第一个例子hello.py:
from sanic import Sanic
from sanic.response import json
from sanic.exceptions import NotFound
app = Sanic(name="pyapp")
@app.route('/')
async def test(request):
return json({'hello': 'world'})
if __name__ == '__main__':
app.error_handler.add(
NotFound,
lambda r, e: sanic.response.empty(status=404)
)
app.run(host&#