Python 异步Web框架Sanic
注: 本文参考 Sanic官方文档 编写:
安装Sanic
pip install sanic # 注意: sanic框架仅支持python3.5+版本
Hello World
- 新建一个文件
hello.py
from sanic import Sanic from sanic.response import json app = Sanic() @app.route("/") async def test(request): return json({"hello": "world"}) if __name__ == "__main__": app.run(host="0.0.0.0", port=8000)
- 运行这个文件:
python3 hello.py
- 打开游览器: http://0.0.0.0:8000
搭建一个后端Web服务器
- 新建一个项目文件夹 如:
NewSanic
- 新建一个配置文件,
settings.py
# 访问配置 HOST = ['*'] PORT = 8000 DEBUG = True
- 新建项目管理文件
manage.py
from NewSanic import settings from NewSanic.urls import app if __name__ == '__main__': app.run( host="0.0.0.0" if settings.HOST[0] == '*' else settings.HOST[0], port=settings.PORT or 8000, debug=settings.DEBUG )
- 新建一个
apis
文件夹, 用来存放不同类型的视图API- 创建一个简单的
view.py
文件
from sanic.response import json, text, html, redirect async def test(request): """返回json""" print(type(request), request) context = {"hello": "world"} return json(context) async def tag_test(request, arg): """get 传参""" print(request.url) print(request.host) print(request.ip) print(request.path) print(request.app.name) return text('arg is {}'.format(arg)) async def html_test(request): """html对象""" return html('<h1>this is html h1 tag') async def redirect_test(request): """重定向""" return redirect(to='/test/html/', content_type='text/html; charset=utf-8')
- 创建一个简单的
- 在项目根目录创建一个公用的
urls.py
文件, 用来存放所有的路由from sanic import Sanic from NewSanic.apis.view import test, tag_test, html_test, redirect_test app = Sanic(name='first_app') app.add_route(test, '/') app.add_route(html_test, "/test/html/") app.add_route(redirect_test, "/test/redirect/") app.add_route(tag_test, "/test/<arg>/")
- 至此, 一个由Sanic搭建的Web服务器已经完成, 执行以下命令启动项目:
python manage.py