Gunicorn 是一个 Python WSGI HTTP 服务器,用于将 Python 应用程序部署到 Web 服务器上。它可以独立运行,也可以与 Nginx、Apache 等 Web 服务器配合使用。

以下是将 Gunicorn 作为服务运行的步骤:

  1. 安装 Gunicorn

使用 pip 安装 Gunicorn:

pip install gunicorn
  1. 编写应用程序

编写一个简单的 Python 应用程序,例如:

# app.py
def application(environ, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    body = b'Hello, World!'
    start_response(status, headers)
    return [body]

这是一个最简单的 WSGI 应用程序,返回一个 'Hello, World!' 字符串。

  1. 运行 Gunicorn

使用以下命令运行 Gunicorn:

gunicorn app:application

其中,app 是应用程序文件名,application 是应用程序中的 WSGI 应用程序对象名。

  1. 测试应用程序

在浏览器中访问 http://localhost:8000,应该可以看到 'Hello, World!' 字符串。

  1. 配置 Gunicorn

可以使用命令行参数或配置文件来配置 Gunicorn。例如,以下命令将 Gunicorn 运行在 4 个进程中:

gunicorn app:application --workers 4

或者,可以创建一个配置文件 gunicorn.conf,内容如下:

workers = 4
bind = '127.0.0.1:8000'

然后使用以下命令运行 Gunicorn:

gunicorn app:application -c gunicorn.conf

这样就可以将 Gunicorn 作为服务运行,并且可以根据需要进行配置。

Gunicorn 服务部署指南:快速运行 Python Web 应用

原文地址: https://www.cveoy.top/t/topic/jEBg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录