> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何使用 Gunicorn

> 了解如何使用 Gunicorn，一个 Python HTTP 服务器。

## 简介

* 本文将引导你完成使用 Gunicorn（一个 Python WSGI HTTP 服务器）的过程。
* 在开始之前，请确保你的环境中已安装 Python 和 Gunicorn。你可以使用以下命令安装 Gunicorn：

```bash theme={null}
pip install gunicorn
```

## 基本用法

要使用 Gunicorn 运行 Python Web 应用程序，你需要有一个 WSGI 应用，例如 flask、django 或其他框架。\
准备好应用之后，你需要知道包含 WSGI 应用对象的模块名和变量名。\
例如，如果你有一个位于名为 `app.py` 文件中的 Flask 应用，且 Flask 实例名为 `app`，你可以使用以下命令通过 Gunicorn 运行它：

```bash theme={null}
python -m gunicorn --bind 0.0.0.0:80 app:app 
```

在此命令中：

* `python -m gunicorn` 将 Gunicorn 作为一个 python 模块运行。
* `--bind 0.0.0.0:80` 告诉 Gunicorn 在所有网络接口的 80 端口上监听。
* `app:app` 指定了包含 WSGI 应用对象的模块名（`app`）和变量名（`app`）。

## 其他选项

Gunicorn 提供了若干选项来自定义其行为。这里我们将展示一些选项。

### Workers

* `--workers <number>`

此选项设置用于处理请求的工作进程数量。通常每个 CPU 核心使用 2-4 个工作进程。\
你可以使用以下公式计算工作进程数量：`(2 x $num_cores) + 1`。

### Name

* `--name <name>`
* `-n <name>`

此选项设置 Gunicorn 的进程名称。

### Worker-class

* `--worker-class <class>`
* `-k <class>`

此选项设置要使用的工作进程类型。默认值为 `sync`，但你也可以使用 `gevent`、`eventlet`、`tornado` 或其他工作进程类型。

### Paste

* `--paste <configfile>`

此选项允许你加载一个 PasteDeploy 配置文件。
这对于像 Pyramid 和 Turbogear 这样使用 PasteDeploy 文件的框架很有用。

## 附加内容

Gunicorn 还有更多选项和功能，你可以在[官方文档](https://docs.gunicorn.org/en/stable/settings.html)中探索。

### 配置文件

* 你也可以创建一个配置文件来设置 Gunicorn 选项。
  该文件可以采用 Python 格式，并命名为 `gunicorn.config.py`。

```python gunicorn.config.py theme={null}
import multiprocessing

bind = "0.0.0.0:80"
workers = multiprocessing.cpu_count() * 2 + 1
```

## 你喜欢这篇文章吗？

* 我们精心创作了这些内容，只为提供尽可能好的帮助。
  如果这篇文章对你有任何帮助，请支持我们的工作！留下你的评价！这能帮助我们了解什么对你最重要。

<CardGroup cols={2}>
  <Card title="Google Reviews" icon="google" href="https://g.page/r/CYZenpQcDgTzEAI/review">
    在 Google Reviews 上留下你的评价。
  </Card>

  <Card title="Trustpilot" icon="star" href="https://www.trustpilot.com/review/squarecloud.app">
    在 Trustpilot 上留下你的评价。
  </Card>
</CardGroup>
