gunicorn 简介

gunicorn是一个python Wsgi http server,只支持在Unix系统上运行,来源于Ruby的unicorn项目。Gunicorn使用prefork master-worker模型(在gunicorn中,master被称为arbiter),能够与各种wsgi web框架协作。gunicorn的文档是比较完善的,这里也有部分中文翻译,不过还是建议直接读英文文档。笔者并没有在项目中真正使用过gunicorn,阅读其源码只要是为了了解其master worker模型,如有纰漏,还请多多指教。

 
  gunicorn的安装非常简单,pip install guncorn 即可。后续如果用到异步的worker模型,还需要安装对应的模块(如gevent)
  在装好gunicorn之后, 我们来看看gunicorn的hello world。代码来自官网,将下面的代码放到gunicorn_app.py中:
  
复制代码
1     def app(environ, start_response):
2         data = b"Hello, World!\n"
3         start_response("200 OK", [
4             ("Content-Type", "text/plain"),
5             ("Content-Length", str(len(data)))
6         ])
7  
8         return iter([data])
复制代码

  可以看到app是非常标准的wsgi应用,然后我们启动gunicorn:gunicorn -w 2 gunicorn_app:app。 输出如下:

  

  上图展示了两个很重要的信息:
   第一:启动了两个worker,这是通过"-w 2"指定(默认为1)
   第二:worker的工作模型是sync(默认),后面会详细介绍worker模型
 
  然后在另外一个terminal运行:ps -ef | grep python 
  
  可以看出 worker进程(pid:19469, 19470)是master进程(pid:19464)的子进程。
 
  新起一个terminal,用curl测试:  curl 127.0.0.1:8000
  在该terminal输出“Hello, World!”

猜你喜欢

转载自www.cnblogs.com/cheyunhua/p/10708703.html
今日推荐