部署 Python Web Server

部署工具介绍

Python 是可以直接运行一个 Python Web Server 的,Python -m SimpleHTTPServer 8000就可以启动一个监听 8000 端口的 Web Server,不像是 php 需要一个 Web Server来配合开发。

Python 的 Web 框架有很多,最具名气的是 Django,flask,tornado,web.py 等,当写一个小的项目的时候我们会直接通过框架提供的启动方式。当要正式部署一个 Web Server时并不能使用如此粗暴的方式,Server 很容易出现异常就挂掉。那么解决方案有很多。

以下是软件介绍,都可使用 pip 直接安装。

Supervisor

Supervisor 是很强大的进程管理工具,也是守护进程,帮你管理服务器上所运行的程序,守护程序防止被杀掉。可以通过写配置文件来批量启动你的 Web Server。

Gunicorn

一款 Wsgi HTTP Server,据说是比 uwsgi 更加高效,但是实测并没有 uwsgi 强。但是部署应用简单。

example: test.py

1
2
3
4
5
6
7
8
9
10
def app(environ, start_response):
"""Simplest possible application object"""
data = '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

启动方便,具体参数请看 gunicorn 文档 http://docs.gunicorn.org/en/latest/

uWsgi

这是我要说的重点,自测吞吐量是其他两种部署方式的两倍。

使用 Flask,uWsgi 和 Nginx 来部署 Server

flask run.py

1
2
3
4
5
6
7
import Flask

app = Flask(__name__)

@app.route('/')
def index():
return "Hello World!"

uwsgi 支持 xml,json,ini 等多种配置文件,我们来配置 testapp.ini

uwsgi testapp.ini

1
2
3
4
5
6
[uwsgi]
socket = /var/run/testapp.sock
venv = /path/to/python
wsgi-file = run.py
callable = app
chmod-socket = 666

/var/run 必须有可写权限,chmod-socket 是避免 nginx 无法读写导致502错误,接下来配置nginx

nginx server.conf

1
2
3
4
5
6
7
8
9
server {
listen 80;
server_name localhost;

location / {
include uwsgi_params;
uwsgi_pass unix:/var/run/testapp.sock;
}
}

这样可以成功部署了,访问 curl http://localhost 输出 Hello World! 部署成功。

更多可以看文档https://uwsgi-docs.readthedocs.io/en/latest/

与 Nginx 配合使用效果更好

早起最流行的是 LAMP,记得初学 Linux 让我们编译 LAMP,一干就是一天。慢慢的 Shell 用的都很熟练了。但是 Apache 用起来就很复杂,第一次使用 Apache 和 Django 部署搞 wsgi_mod 花了很长时间。之后使用了 Nginx 才算是彻底在部署 Web Server 上解放。配置简单,部署方便,轻量且强大。

Nginx 是不可少的,路由管理、静态文件管理,Gzip,HTTPS、HTTP2/SPDY、ETAG 都需要 Nginx 来 handle。

测试

使用 ab 测试工具 ab -c 10 -n 100 http://localhost/ 模拟10人请求 localhost 100次。

守护进程

Web Server 使用 uwsgi 或者 gunicorn ,都是需要守护进程来守护 Server 不被杀掉。这时再使用 supervisor 就可以了。