开始

在开始前请确保你同时安装了 pip 和至少 3.5 以上版本的 Python 。Sanic 使用了新的 async/await 语法,所以之前的版本无法工作。

  1. 安装 Sanic: python3 -m pip install sanic
  2. 新建一个叫 main.py 的文件并且附上以下代码:

    1. from sanic import Sanic
    2. from sanic.response import json
    3. app = Sanic()
    4. @app.route("/")
    5. async def test(request):
    6. return json({"hello": "world"})
    7. if __name__ == "__main__":
    8. app.run(host="0.0.0.0", port=8000)
  3. 启动服务器: python3 main.py

  4. 在你的浏览器打开地址 http://0.0.0.0:8000。你会看到 Hello world!

现在你已经会用 Sanic 了!