当前位置:首页 > 技术文章 > 正文内容

Python WSGI 高性能服务器 - Gunicorn 简介

arlanguage5个月前 (12-12)技术文章63

一、简介

Gunicorn 意即 Green Unicorn,绿色独角兽。它是一个被广泛使用的高性能的 Python WSGI UNIX HTTP服务器,移植自Ruby的独角兽(Unicorn )项目。

它具有如下特性:

  • 原生支持 WSGI、Django 和 Paster
  • 自动工作进程管理
  • 简单的 Python 配置
  • 多个 worker 配置
  • 多种可扩展性服务器挂钩
  • 兼容 Python 3.x >= 3.5

二、安装

$ pip install gunicorn
复制代码

或者从源码安装:

$ pip install git+https://github.com/benoitc/gunicorn.git
复制代码

如果你需要使用异步 workers,你还需要安装:

$ pip install greenlet            # Required for both
$ pip install eventlet            # For eventlet workers
$ pip install gunicorn[eventlet]  # Or, using extra
$ pip install gevent              # For gevent workers
$ pip install gunicorn[gevent]    # Or, using extra
复制代码

三、使用

假如你有以下应用:

def app(environ, start_response):
    """Simplest possible application object"""
    data = b'Hello, World!\n'
    status = '200 OK'
    response_headers = [
        ('Content-type', 'text/plain'),
        ('Content-Length', str(len(data)))
    ]
    start_response(status, response_headers)
    return iter([data])
复制代码

命令行启动:

$ gunicorn --workers=2 test:app
复制代码

也可以使用工厂模式:

def create_app():
    app = FrameworkApp()
    ...
    return app
复制代码

命令行启动:

$ gunicorn --workers=2 'test:create_app()'
复制代码

四、配置

Gunicorn从5个地方依次读取配置:

  1. 环境变量
  2. 框架配置
  3. gunicorn.conf.py 配置文件
  4. 环境变量中的 GUNICORN_CMD_ARGS
  5. 命令行

常见配置项:

  • --config 配置文件
  • --reload 代码更改时重新启动
  • --access-logfile 要写入的访问日志文件
  • --error-logfile 要写入的错误日志文件
  • --log-level 错误输出级别
  • --certfile SSL证书文件
  • --bind 绑定socket
  • --workers 处理请求的工作进程数
  • --threads 用于处理请求的工作线程数

五、服务器钩子

  • on_starting 在主进程初始化之前调用
  • on_reload 重新加载期间调用
  • when_ready 在服务器启动后立即调用
  • pre_fork 在fork之前调用
  • post_fork 在fork之后调用
  • post_worker_init 在work初始化之后调用
  • worker_int 在worker 退出 SIGINT 或 SIGQUIT 后立即调用
  • worker_abort 在worker 收到SIGABRT 信号时调用
  • pre_exec 新的主进程之前调用
  • pre_request 处理请求之前调用
  • post_request 处理请求后调用
  • child_exit 在主进程中退出工作程序后立即调用
  • worker_exit worker退出后调用
  • nworkers_changed 在_num_workers_更改后_立即_调用
  • on_exit 在退出 Gunicorn 之前调用

六、部署

官方强烈建议在代理服务器后面使用 Gunicorn。

Nginx:

尽管有许多可用的 HTTP 代理,但官方建议您使用 Nginx。

Nginx配置文件示例:

worker_processes 1;

user nobody nogroup;
# 'user nobody nobody;' for systems with 'nobody' as a group instead
error_log  /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
  worker_connections 1024; # increase if you have lots of clients
  accept_mutex off; # set to 'on' if nginx worker_processes > 1
  # 'use epoll;' to enable for Linux 2.6+
  # 'use kqueue;' to enable for FreeBSD, OSX
}

http {
  include mime.types;
  # fallback in case we can't determine a type
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log combined;
  sendfile on;

  upstream app_server {
    # fail_timeout=0 means we always retry an upstream even if it failed
    # to return a good HTTP response

    # for UNIX domain socket setups
    server unix:/tmp/gunicorn.sock fail_timeout=0;

    # for a TCP configuration
    # server 192.168.0.7:8000 fail_timeout=0;
  }

  server {
    # if no Host match, close the connection to prevent host spoofing
    listen 80 default_server;
    return 444;
  }

  server {
    # use 'listen 80 deferred;' for Linux
    # use 'listen 80 accept_filter=httpready;' for FreeBSD
    listen 80;
    client_max_body_size 4G;

    # set the correct host(s) for your site
    server_name example.com www.example.com;

    keepalive_timeout 5;

    # path for static files
    root /path/to/app/current/public;

    location / {
      # checks for static file, if not found proxy to app
      try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Host $http_host;
      # we don't want nginx trying to do something clever with
      # redirects, we set the Host: header above already.
      proxy_redirect off;
      proxy_pass http://app_server;
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root /path/to/app/current/public;
    }
  }
}
复制代码

如果您希望能够处理流请求/响应或其他功能,如 Comet、长轮询或 Web sockets,您需要关闭代理缓冲。**执行此操作时,**您必须使用异步worker 。

要关闭缓冲,您只需要设置:proxy_buffering off;

...
location @proxy_to_app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_buffering off;

    proxy_pass http://app_server;
}
... 
复制代码

建议将协议信息传递给 Gunicorn。许多 Web 框架使用此信息来生成 URL。如果没有此信息,应用程序可能会错误地在“https”响应中生成“http”URL,从而导致混合内容警告或应用程序损坏,设置proxy_set_header 即可:

...
proxy_set_header X-Forwarded-Proto $scheme;
...
复制代码

如果您在不同的主机上运行 Nginx,您需要告诉 Gunicorn 信任X-Forwarded-*。默认情况下,Gunicorn 只会信任 localhost 的这些标头。这是为了防止客户端恶意伪造这些标头:

 gunicorn -w 3 --forwarded-allow-ips="10.170.3.217,10.170.3.220" test:app

扫描二维码推送至手机访问。

版权声明:本文由AR编程网发布,如需转载请注明出处。

本文链接:http://www.arlanguage.com/post/123.html

标签: nginx if 数字
分享给朋友:

“Python WSGI 高性能服务器 - Gunicorn 简介” 的相关文章

nginx 多域名配置 nginx多站点配置示例

Nginx 可以配置多个域名,以便根据不同的域名来处理不同的请求。下面是一个配置多个域名的例子:server { listen 80; server_name example1.com; location / { root /var/www/example1...

了解PHP-FPM

在服务器上,当我们查看php进程时,全都是php-fpm进程,大家都知道这个就是php的运行环境,那么,它到底是个什么东西呢?PHP-FPM简介PHP-FPM,就是PHP的FastCGI管理器,用于替换PHP FastCGI的大部分附加功能,在PHP5.3.3后已经成为了PHP的标配。有小伙伴要问了...

WordPress切换到Nginx服务器教程

这几天将几个WordPress的Web服务器从Apache切换到了Nginx,中间遇到了不少问题,因此记录一下,以便日后维护使用。对于WordPress站点来说,固定链接主要是通过根目录下的.htaccess文件来控制,切换服务器后,Nginx的rewrite格式和Apache的不同,需要修改。先卸...

nginx命令——学习记录 nginx详细教程

nginx命令--学习记录查看80端口是否被占用netstat -ntlpnginx命令#/usr/local/nginx/sbin/nginx 启动命令#/usr/local/nginx/sbin/nginx -t 检测配置文件 #/usr/local/nginx/sbin/ngin...

nginx入门——nginx访问日志(六)

日志功能在ngx_http_log_module模块中定义,实现了以指定格式写入请求日志。我们先来看一个nginx配置文件:http { include mime.types; default_type application/octet-stream;...

Nginx 重定向 HTTP 到 HTTPS 的便捷方法

问题描述 自从大规模使用 HTTPS 之后,所有的 HTTP 访问都要重定向到 HTTPS 站点。不然,客户只会输入域名,而很多浏览器又默认使用 HTTP 协议,如果我们没有提供 HTTP 访问,又不重定向,那客户将看到一个空白页(无法访问),客户会以为我们的站点有问题,毕竟客户哪里知道什么是 HT...