Flask + Gunicorn + Nginx 部署

WSGI协议

Web框架致力于如何生成HTML代码,而Web服务器用于处理和响应HTTP请求。Web框架和Web服务器之间的通信,需要一套双方都遵守的接口协议。WSGI协议就是用来统一这两者的接口的。

WSGI容器——Gunicorn

常用的WSGI容器有Gunicorn和uWSGI,但Gunicorn直接用命令启动,不需要编写配置文件,相对uWSGI要容易很多,所以这里我也选择用Gunicorn作为容器。

安装

pip install gunicorn

启动

$ gunicorn [options] module_name:variable_name

module_name对应python文件,variable_name对应web应用实例。
以最简单的flask应用为例:

#main.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return 'hello world'
    
if __name__ == '__main__':
    app.run()

启动代码:

gunicorn --worker=3 main:app -b 0.0.0.0:8080

tips

开发flask应用时,常用flask-script添加一些命令扩展。而部署应用时,就不需要再从flask-script的Manager实例中启动应用了。
在项目中添加wsgi.py文件:

# -*- coding: utf-8 -*-
import os

from . import create_app
import datetime

# Create an application instance that web servers can use. We store it as
# "application" (the wsgi default) and also the much shorter and convenient
# "app".
application = app = create_app('default')

@app.context_processor
def template_extras():
    """
    上下文处理装饰器,返回的字典的键可以在上下文中使用
    :return:
    """
    return {'enumerate': enumerate, 'len': len, 'datetime': datetime}
  • 在wsgi文件中创建flask实例给gunicorn使用。
  • 创建实例后,注册上下文装饰器。

再通过gunicorn启动flask应用:

gunicorn -b 127.0.0.1:8000 -k gevent -w 1 app.wsgi

Nginx

Gunicorn对静态文件的支持不太好,所以生产环境下常用Nginx作为反向代理服务器。

安装

sudo apt-get install nginx

启动

sudo /etc/init.d/nginx start

修改配置文件

先将配置文件备份:

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak

然后修改配置文件:

server {
        listen 80;
        server_name _; # 外部地址

        location / {
                proxy_pass http://127.0.0.1:8000;
                proxy_redirect     off;
                proxy_set_header   Host                 $http_host;
                proxy_set_header   X-Real-IP            $remote_addr;
                proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Proto    $scheme;
        }

这里将Nginx设置为代理模式,代理到本地的8000端口,之后就可以通过公网访问flask应用了。

总结

最后,总结下这几个部分的关系:


(nginx收到客户端发来的请求,根据nginx中配置的路由,将其转发给WSGI)
nginx:"WSGI,找你的来了!"
(WSGI服务器根据WSGI协议解析请求,配置好环境变量,调用start_response方法呼叫flask框架)
WSGI服务器:"flask,快来接客,客户资料我都给你准备好了!"
(flask根据env环境变量,请求参数和路径找到对应处理函数,生成html)
flask:"!@#$%^......WSGI,html文档弄好了,拿去吧。"
(WSGI拿到html,再组装根据env变量组装成一个http响应,发送给nginx)
WSGI服务器:"nginx,刚才谁找我来着?回他个话,!@#$%^....."
(nginx再将响应发送给客户端)

Comments
Write a Comment