1. what is gunicorn#
1.1 definition#
Gunicorn 'Green Unicorn' is a Python WSGI HTTP Server for UNIX. It's a pre-fork worker model. The Gunicorn server is broadly compatible with various web frameworks, simply implemented, light on server resources, and fairly speedy.
1.2 characteristics#
- Gunicorn是基于prefork模式的Python wsgi应用服务器,支持 Unix like的系统
- 采用epoll (Linux下) 非阻塞网络I/O 模型
- 多种Worker类型可以选择 同步的,基于事件的(gevent tornado等),基于多线程的
- 高性能,比之uwsgi不相上下
- 配置使用非常简单
- 支持 Python 2.x >= 2.6 or Python 3.x >= 3.2
2. how to use#
2.1 install#
1 | pip install gunicorn |
2.2 start#
1 | $ gunicorn [options] module_name:variable_name |
module_name对应python文件,variable_name对应web应用实例
2.3 基础example#
编写简单的myapp.py:
1
2
3
4
5
6
7
8def app(version, start_response):
logging.info("version: %s" % version)
data = b"hello, world! \n"
start_response("200 OK", [
("Content-Type", "text/plain"),
("Content-Length", str(len(data)))
])
return iter([data])
启动gunicorn
1
gunicorn myapp:app -b localhost:8080
使用curl访问8080端口
1
2$ curl localhost:8080
hello, world!
2.4 使用flask搭建简单的web服务器#
编写myflask.py
1
2
3
4
5
6from flask import Flask
app = Flask(__name__)
@app.route('/demo', methods=['GET'])
def demo():
return "gunicorn and flask demo.\n"1
2
3
4
5$ ls -lh
total 4.0K
drwxr-xr-x 2 xxx xxx 92 Oct 18 15:12 log
drwxr-xr-x 2 xxx xxx 120 Oct 18 17:41 script
-rw-r--r-- 1 xxx xxx 657 Oct 18 14:16 start.sh
为了启动方便, 写个简单的start.sh启动脚本如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18lsof -i :$2|grep gunicorn|awk '{print $2}'|xargs kill -9 # kill掉原来该端口上 gunicorn进程
cd script
if [ -z "$3" ]; then
nohup gunicorn --workers=1 $1:app -b localhost:$2 1>../log/log.${2}_${1} 2>&1 & # 未指定进程数
else
nohup gunicorn --workers=$3 $1:app -b localhost:$2 1>../log/log.${2}_${1} 2>&1 &
fi
sleep 1.5s
info=`lsof -i :$2|grep gunicorn`
# echo ${info}
if [ -z "$info" ]; then
echo "Something wrong~ Fail to start gunicorn!"
else
echo "succeed starting gunicorn which port is $2 and which script's name is $1"
fi1
2
3$ sh start.sh myflask 8090 2
succeed starting gunicorn which port is 8090 and which script's name is myflask
测试下是否ok
1
2$ curl localhost:8090/demo
gunicorn and flask demo.