# Windows 上的 Python WSGI：Waitress 放在 IIS/Nginx 后面

> 在 venv 里用 Waitress 跑 WSGI 应用，做成服务，再反代；不要把 Gunicorn 命令搬到 Windows。

**测试环境**

- 版本号: 26100.33650
- 版本: Standard / Datacenter
- 架构: x64
- 证据: E1
- 核验日期: 2026-10-29

## 一句话结论

Windows 上用 **Waitress** 做 WSGI 服务器：

```powershell
C:\apps\api-a\.venv\Scripts\python.exe -m pip install waitress
C:\apps\api-a\.venv\Scripts\python.exe -m waitress --listen=127.0.0.1:8000 app:app
```

再让 IIS（HttpPlatformHandler/ARR）或 Nginx 在前面。Gunicorn 是 Unix-only，不要把 Gunicorn 命令抄到 Windows。

## 为什么 Waitress

- 纯 Python，Windows 可用；
- 多线程，不 fork；
- 兼容 WSGI（Flask/Django）；
- `--listen` 和线程数简单。

它不是进程管理器。用服务包装器（NSSM/WinSW）保活。

## 服务包装

```bat
nssm install api-a "C:\apps\api-a\.venv\Scripts\python.exe" "-m waitress --listen=127.0.0.1:8000 app:app"
nssm set api-a AppDirectory "C:\apps\api-a"
nssm set api-a AppEnvironmentExtra APP_ENV=production
nssm set api-a AppStdout "C:\logs\api-a\out.log"
nssm set api-a AppStderr "C:\logs\api-a\err.log"
nssm start api-a
```

固定 venv python，不用 PATH 的 `python`。设置 `AppDirectory`，相对模板/配置才能解析。

## IIS 在前面

两种：

- **HttpPlatformHandler** 启动 Python 进程，IIS 管生命周期（见 HPH 页）。
- **ARR** 反代到 `127.0.0.1:8000`；Python 进程作为服务跑。

同一端口不要两种都做。选一个监管者。

## Nginx 在前面

```nginx
location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}
```

应用要信任代理头；否则重定向/绝对 URL 会用内部主机名。

## 验证

```powershell
C:\apps\api-a\.venv\Scripts\python.exe -c "import sys; print(sys.executable)"
curl.exe -I http://127.0.0.1:8000/
Get-CimInstance Win32_Process -Filter "Name='python.exe'" |
  Select-Object ProcessId, ExecutablePath, CommandLine
```

`sys.executable` 是 venv，且 8000 只有一个监听进程。

## 线程与超时

小应用从 `--threads=4` 到 `8` 开始；加之前先测。前端代理读超时要大于最慢合法请求。长报表应该异步，不是 30 分钟 HTTP 请求。

> **警告: 生产不要用 Flask 开发服务器**
>
> `flask run`/`app.run()` 是开发用。生产用 Waitress（或其他 Windows 可用 WSGI 服务器），放在 IIS/Nginx 后面，并用服务包装器。

## 实验室边界

E1。实验室没有装 Waitress 或跑 WSGI 应用；命令是 Server 2025 上待验证的 Windows 部署模式。

## 来源

- [Waitress](https://docs.pylonsproject.org/projects/waitress/en/stable/)
- [Python — venv](https://docs.python.org/zh-cn/3/library/venv.html)
- [Microsoft Learn — HttpPlatformHandler](https://learn.microsoft.com/zh-cn/iis/extensions/httpplatformhandler/httpplatformhandler-configuration-reference)

---

来源页面: https://winbook.fyi/zh/server/runtimes/python-wsgi/
