响应器§
要使用 Unit 运行使用 响应器 Web 框架构建的应用
使用 Python 3.6+ 语言模块安装 Unit。
创建虚拟环境来安装响应器的 PIP 软件包
$ cd /path/to/app/ $ python3 --version Python 3.Y.Z $ python3 -m venv venv $ source venv/bin/activate $ pip install responder $ deactivate
警告
使用与步骤 1 中的语言模块相匹配的 Python 版本(在此示例中为 3.Y)创建虚拟环境。此外,步骤 5 中的应用 类型 必须 解析 为类似的匹配版本;Unit 不会从环境中推断它。
让我们尝试一个 教程应用 的 Unit 友好版本,将其保存为 /path/to/app/asgi.py
import responder app = responder.API() @app.route("/") def hello_world(req, resp): resp.text = "Hello, World!" @app.route("/hello/{who}") def hello_to(req, resp, *, who): resp.text = f"Hello, {who}!"
省略了 app.run() 调用,因为 app 将由 Unit 直接作为 ASGI 可调用对象 运行。
运行以下命令,以便 Unit 可以访问 应用程序目录
# chown -R unit:unit /path/to/app/
有关更多详细信息,包括权限,请参见 安全检查清单。
接下来,准备 Unit 的响应器配置(对 类型、主页 和 路径 使用实际值)
{ "listeners": { "*:80": { "pass": "applications/responder" } }, "applications": { "responder": { "type": "python 3.Y", "path": "/path/to/app/", "home": "/path/to/app/venv/", "working_directory": "/path/to/app/", "module": "asgi", "callable": "app" } } }
上传更新后的配置。假设上述 JSON 已添加到
config.json
# curl -X PUT --data-binary @config.json --unix-socket \ /path/to/control.unit.sock http://localhost/config/
成功更新后,您的应用应可在侦听器的 IP 地址和端口上使用
$ curl http://localhost Hello, World! $ curl http://localhost/hello/JohnDoe Hello, JohnDoe!