Python Pyramid - 部署



本教程中迄今为止开发的 Pyramid 应用示例已在本地机器上执行。为了使其公开访问,必须将其部署到能够支持 WSGI 标准的生产服务器上。

为此,可以使用许多兼容 WSGI 的 HTTP 服务器。例如:

  • waitress
  • paste.httpserver
  • CherryPy
  • uWSGI
  • gevent
  • mod_wsgi

我们已经讨论了如何使用 Waitress 服务器来托管 Pyramid 应用。它可以在具有公共 IP 地址的机器的 80(HTTP)和 443(HTTPS)端口上运行。

mod_wsgi

Apache 服务器是一种流行的开源 HTTP 服务器软件,由 Apache 软件基金会发行。它为互联网上的大多数 Web 服务器提供支持。mod_wsgi(由Graham Dumpleton开发)是一个 Apache 模块,它提供了一个 WSGI 接口,用于在 Apache 上部署基于 Python 的 Web 应用。

在本节中,将解释在 Apache 服务器上部署 Pyramid 应用的分步过程。在这里,我们将使用 XAMPP,这是一个流行的开源 Apache 发行版。它可以从https://www.apachefriends.org/download.html下载。

mod_wsgi 模块使用 PIP 安装程序安装。在安装之前,请将 MOD_WSGI_APACHE_ROOTDIR 环境变量设置为 Apache 可执行文件所在的目录。

C:\Python310\Scripts>set MOD_WSGI_APACHE_ROOTDIR=C:/xampp/apache
C:\Python310\Scripts>pip install mod_wsgi

接下来,在命令终端运行以下命令。

C:\Python310\Scripts>mod_wsgi-express module-config
LoadFile "C:/Python310/python310.dll"
LoadModule wsgi_module "C:/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd"
WSGIPythonHome "C:/Python310"

这些是需要添加到 Apache 配置文件的 mod_wsgi 模块设置。打开 XAMPP 安装的httpd.conf文件,并将上述命令行的输出复制到其中。

接下来,为我们的应用创建一个虚拟主机配置。Apache 将虚拟主机信息存储在httpd-vhosts.conf文件中,该文件位于 C:\XAMPP\Apache\conf\extra\ 文件夹中。打开该文件并在其中添加以下几行:

<VirtualHost *>
   ServerName localhost:6543
   WSGIScriptAlias / e:/pyramid-env/hello/production.ini
   <Directory e:/pyramid-env/hello>
      Order deny,allow
      Allow from all
      Require all granted
   </Directory>
</VirtualHost>

这里假设使用 Cookiecutter 实用程序构建了一个 hello Pyramid 项目。这里使用了在生产环境中使用的 PasteDeploy 配置文件。

需要将此虚拟主机配置添加到 Apache 的 httpd.conf 文件中。这可以通过在其中添加以下几行来完成:

# Virtual hosts
   Include conf/extra/httpd-vhosts.conf

现在,我们必须将以下代码保存为pyramid.wsgi文件,该文件返回 Pyramid WSGI 应用对象。

from pyramid.paster import get_app, setup_logging
ini_path = 'e:/pyramid-env/hello/production.ini'
setup_logging(ini_path)
application = get_app(ini_path, 'main')

完成上述步骤后,重新启动 XAMPP 服务器,我们应该能够在 Apache 服务器上运行 Pyramid 应用。

在 Uvicorn 上部署

Uvicorn 是一个兼容 ASGI 的服务器(ASGI 代表异步网关接口)。由于 Pyramid 是一个基于 WSGI 的 Web 框架,我们需要借助asgiref.wsgi模块中定义的WsgiToAsgi()函数,将 WSGI 应用对象转换为 ASGI 对象。

from asgiref.wsgi import WsgiToAsgi
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
   return Response("Hello")
   
with Configurator() as config:
   config.add_route("hello", "/")
   config.add_view(hello_world, route_name="hello")
   wsgi_app = config.make_wsgi_app()
   
app = WsgiToAsgi(wsgi_app)

将上述代码保存为 app.py。使用 pip 实用程序安装 Uvicorn。

pip3 install uvicorn

在 ASGI 模式下运行 Pyramid 应用。

uvicorn app:app

同样,它可以使用daphne服务器运行。

daphne app:app
广告
© . All rights reserved.