03-安装运行 Sanic

  • 阅读: 547
  • 更新: 2022-04-22

Sanic 是 Python3.7+ Web 服务器和 Web 框架,旨在提高性能。
在我们开始之前,请确保您使用的是 Python3.7 或更高版本。目前已知可以使用的 Python 版本包括:3.7,3.8 和 3.9。

1. 安装

1
pip install sanic

如果你使用 pipenv 管理 python 的多环境:

1
pipenv install sanic

2. 新创建一个 sanic 应用

新建一个目录,然后新建一个 server.py 文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from sanic import Sanic
from sanic.response import text

app = Sanic("MyAPP")


@app.get("/")
async def hello_world(request):
    return text("Hello, world.")


if __name__ == '__main__':
    app.run(debug=True, auto_reload=True)

3. 运行

1
python server.py

运行输出如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
[2022-04-22 23:09:08 +0800] [222] [INFO]
  ┌──────────────────────────────────────────────────────────────────────────────────────────────┐
  │                                        Sanic v22.3.0                                         │
  │                              Goin' Fast @ http://127.0.0.1:8000                              │
  ├───────────────────────┬──────────────────────────────────────────────────────────────────────┤
  │                       │        mode: debug, single worker                                    │
  │     ▄███ █████ ██     │      server: sanic                                                   │
  │    ██                 │      python: 3.8.5                                                   │
  │     ▀███████ ███▄     │    platform: Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29 │
  │                 ██    │ auto-reload: enabled                                                 │
  │    ████ ████████▀     │    packages: sanic-routing==22.3.0                                   │
  │                       │                                                                      │
  │ Build Fast. Run Fast. │                                                                      │
  └───────────────────────┴──────────────────────────────────────────────────────────────────────┘

[2022-04-22 23:09:08 +0800] [222] [DEBUG] Dispatching signal: server.init.before
[2022-04-22 23:09:08 +0800] [222] [DEBUG] Dispatching signal: server.init.after
[2022-04-22 23:09:08 +0800] [222] [INFO] Starting worker [222]

可以看到有几个非常有用的字段:

  • mode, 是否开启了 debug,以及子进程 worker 的数量
  • auto-reload, 是否开启了自动重载

4. 访问

运行输出中会有访问链接,默认是本机 8000 端口;访问地址为:http://127.0.0.1:8000

访问之后能看到浏览器打印的 Hello, world.


=== 全文完 ===


欢迎加入QQ群:855013471

京公网安备 11011302003970号 京ICP备2022012301号-1