Gunicorn、uWSGI初探

55 阅读1分钟

Gunicorn 介绍与 Demo

Gunicorn(Green Unicorn)是一个 Python WSGI HTTP 服务器,支持多进程并发,常用于部署 Flask、Django 等 Web 应用。

安装:

pip install gunicorn

Demo: 假设有一个 app.py 文件:

# app.py
def app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return [b'Hello from Gunicorn!']

启动:

gunicorn app:app

uWSGI 介绍与 Demo

uWSGI 是一个高性能的 WSGI/Web 服务器,支持多种协议和语言,常用于生产环境部署。

安装:

pip install uwsgi

Demo: 假设有一个 app.py 文件:

# app.py
def app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return [b'Hello from uWSGI!']

启动:

uwsgi --http :8000 --wsgi-file app.py --callable app

下面分别给出 Gunicorn 和 uWSGI 的 Flask/Django 示例及常用参数说明。


Flask 示例

app.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello from Flask!'

Gunicorn 启动:

gunicorn app:app --workers 4 --bind 0.0.0.0:8000

uWSGI 启动:

uwsgi --http :8000 --wsgi-file app.py --callable app --processes 4 --threads 2

Django 示例

假设 Django 项目名为 mysitemysite/wsgi.py 是默认 WSGI 入口。

Gunicorn 启动:

gunicorn mysite.wsgi:application --workers 4 --bind 0.0.0.0:8000

uWSGI 启动:

uwsgi --http :8000 --module mysite.wsgi:application --processes 4 --threads 2

常用参数说明

  • --workers / --processes:进程数,提升并发能力。
  • --threads:每进程线程数(uWSGI)。
  • --bind / --http:监听地址和端口。
  • --wsgi-file:WSGI 应用文件(uWSGI)。
  • --callable:WSGI 应用对象名(uWSGI)。
  • --module:Django WSGI 模块(uWSGI)。