NGINX Unit

Pyramid§

要使用 Unit 运行使用 Pyramid Web 框架构建的应用

  1. 使用 Python 3 语言模块安装 Unit

  2. 创建一个虚拟环境来安装 Pyramid 的 PIP 包

    $ cd /path/to/app/
    $ python3 --version
          Python 3.Y.Z
    $ python3 -m venv venv
    $ source venv/bin/activate
    $ pip install pyramid
    $ deactivate
    

    警告

    使用与步骤 1 中的语言模块匹配的 Python 版本(此示例中为 3.Y)创建虚拟环境,直至次要版本号。此外,步骤 5 中的应用 类型 必须 解析 为类似的匹配版本;Unit 不会从环境中推断它。

    注意

    此处,$VENV 未设置,因为 Unit 在步骤 5 中从 home 中获取虚拟环境。

  3. 让我们看看 Pyramid 教程 中的应用如何在 Unit 上运行。

    我们修改 教程应用,将其另存为 /path/to/app/wsgi.py

    from pyramid.config import Configurator
    from pyramid.response import Response
    
    def hello_world(request):
        return Response('<body><h1>Hello, World!</h1></body>')
    
    with Configurator() as config:
        config.add_route('hello', '/')
        config.add_view(hello_world, route_name='hello')
        app = config.make_wsgi_app()
    # serve(app, host='0.0.0.0', port=6543)
    

    请注意,我们已经删除了服务器代码;还要注意,Unit 导入模块,因此 if __name__ == ‘__main__’ 惯用法无关紧要。

    要加载配置,我们在/path/to/app/ 中将wsgi.py 文件放在development.ini 旁边

    from pyramid.paster import get_app, setup_logging
    
    app = get_app('development.ini')
    setup_logging('development.ini')
    

    设置了 Unit 的 WSGI 应用程序;如果.ini 的路径名是相对的,请在 Unit 配置中提供适当的working_directory

  4. 运行以下命令,以便 Unit 可以访问应用程序目录

    # chown -R unit:unit /path/to/app/
    

    注意

    unit:unit 用户组对仅适用于官方软件包、Docker 镜像和一些第三方仓库。否则,帐户名称可能有所不同;运行ps aux | grep unitd 命令以确保这一点。

    有关包括权限在内的更多详细信息,请参阅安全检查清单

  5. 接下来,准备 Unit 的 Pyramid 配置(对typehomepath 使用实际值)

    {
        "listeners": {
            "*:80": {
                "pass": "applications/pyramid"
            }
        },
    
        "applications": {
            "pyramid": {
                "type": "python 3.Y",
                "working_directory": "/path/to/app/",
                "path": "/path/to/app/",
                "home": "/path/to/app/venv/",
                "module": "wsgi",
                "callable": "app"
            }
        }
    }
    
  6. 上传更新后的配置。假设上述 JSON 已添加到config.json

    # curl -X PUT --data-binary @config.json --unix-socket \
           /path/to/control.unit.sock http://localhost/config/
    

    注意

    控制套接字路径可能有所不同;运行unitd -h 或参阅启动和关闭以了解详细信息。

    成功更新后,您的应用程序应可在侦听器的 IP 地址和端口上使用

    $ curl http://localhost
    
          <body><h1>Hello, World!</h1></body>