前言
Sanic是一个支持 async/await
语法的异步无阻塞框架。是类似Flask的框架,但是因为是Sanic是异步的,所以速度比Flask快多了,大家可以试试呀!
正文
来个hello world例子,代码看起来其实和Flask是一样的:
from sanic import Sanic
from sanic.response import json
app = Sanic(__name__)
@app.route("/")
async def test(request):
return json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
也是有路由(@app.route)下面是增加路由的例子哦:
async def handler1(request):
return text('ok')
async def handler2(request, name):
return text('Folder - {}'.format(name))
async def personal_handler2(request, name):
return text('Person - {}'.format(name))
app.add_route(handler1, '/test')
app.add_route(handler2, '/folder/<name>')
app.add_route(personal_handler2, '/personal/<name:[A-z]>', methods=['GET'])
Sanic提供了一个urlfor方法,根据处理程序方法名生成url。避免硬编码url路径到您的应用程序。来个例子:
@app.router("/")
async def index(request):
url = app.url_for('post_handler', post_id=5)
return redirect(url)
其实看起来和Flask是一样的呀!大家可以用Since,但是还是要主要Python版本哦!