Python 的 WSGI 服务器 Gunicorn

Gunicorn 绿色独角兽 是一个Python WSGI UNIX的HTTP服务器。这是一个pre-fork worker的模型,从Ruby的独角兽(Unicorn )项目移植。该Gunicorn服务器大致与各种Web框架兼容,只需非常简单的执行,轻量级的资源消耗,以及相当迅速。

结构图:

uWSGI 的性能比较:

特点:

  • 本身支持WSGI、Django、Paster
  • 自动辅助进程管理
  • 简单的 Python配置
  • 允许配置多个工作环境
  • 各种服务器的可扩展钩子
  • 与 Python 2.x > = 2.5,3.x >= 3.2 兼容

安装:

$ pip install gunicorn
$ cat myapp.py
  # -*- coding: utf-8 -
  from wsgiref.validate import validator
  from gunicorn import __version__
  @validator
  def app(environ, start_response):
      if environ['REQUEST_METHOD'].upper() != 'POST':
         data = b'Hello, World!\n'
      else:
         data = environ['wsgi.input'].read()
      start_response("200 OK", [
          ("Content-Type", "text/plain"),
          ("Content-Length", str(len(data)))
      ])
      print data
      return iter([data])
$ gunicorn -w 4 -b 127.0.0.1:8060 myapp:app
[2014-09-10 10:22:28 +0000] [30869] [INFO] Listening at: http://10.100.67.77:8060 (30869)
[2014-09-10 10:22:28 +0000] [30869] [INFO] Using worker: sync
[2014-09-10 10:22:28 +0000] [30874] [INFO] Booting worker with pid: 30874
[2014-09-10 10:22:28 +0000] [30875] [INFO] Booting worker with pid: 30875
[2014-09-10 10:22:28 +0000] [30876] [INFO] Booting worker with pid: 30876
[2014-09-10 10:22:28 +0000] [30877] [INFO] Booting worker with pid: 30877

测试访问:curl -d “a=b” “http://10.100.67.77:8060”

Nginx:

建议高并发生产环境前置nginx用于负载。

server {
    listen 80;
    server_name example.org; # 这是HOST机器的外部域名,用地址也行

    location / {
        proxy_pass http://127.0.0.1:8060; # 这里是指向 gunicorn host 的服务地址
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

官网:https://pypi.python.org/pypi/gunicorn

欢迎关注下方“非著名资深码农“公众号进行交流~

发表评论

邮箱地址不会被公开。