一直对WSGI比较感兴趣,这东西是所有RestFul HTTP API请求的入口,但是又没咋搞明白,之前看过一点paste deploy的东西,也玩过几把:https://github.com/aspirer/study/tree/master/paste_deploy,但WSGI服务的编写和托管部署都不甚明白,因此动手决定体验一把。之前听同事说过bottle.py这个框架(其他框架也很多:python自带的wsgiref、web.py、flask、django等等),一个文件就搞定所有WSGI基础功能,非常简单轻巧,部署超简单,下载一个文件就能跑,还能集成到很多web框架中,新手用它来体验WSGI服务再合适不过了。官网:https://bottlepy.org/
首先根据官网介绍实现一个WSGI app,全部文件清单如下:
1 2 3 4 5 6 7 |
[root@linux wsgi]# pwd /var/www/wsgi [root@linux wsgi]# ll total 1296 -rw-r--r-- 1 apache apache 332 Dec 14 17:23 app.wsgi ## wsgi入口 -rwxr-xr-x 1 apache apache 150120 Dec 14 11:19 bottle.py ## bottle框架模块 -rw-r--r-- 1 apache apache 197 Dec 14 11:23 hello.py ## 自己的app |
其中文件内容分别为:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import sys, os sys.path = ['/var/www/wsgi/'] + sys.path # Change working directory so relative paths (and template lookup) work again os.chdir(os.path.dirname(__file__)) import bottle import hello ### your app # ... build or import your bottle application here ... # Do NOT use bottle.run() with mod_wsgi application = bottle.default_app() |
1 2 3 4 5 6 7 8 9 10 11 |
from bottle import route, run, template @route('/hello') def hello(): return "Hello World!" @route('/hello/<name>') def index(name): return template('<b>Hello {{name}}</b>!', name=name) run(host='0.0.0.0', port=9090) |
注意,使用Apache、uWSGI托管服务的时候,不需要这行:run(host=’0.0.0.0′, port=9090)
直接运行
之后执行python hello.py就可以跑起来一个简单的WSGI服务了,端口是9090,监听到0.0.0.0,浏览器访问:http://WSGI服务节点IP:9090/hello,就会显示”Hello World!”,访问http://WSGI服务节点IP:9090/hello/abc,就会显示Hello abc!
Apache托管
我是Centos7系统,安装Apache及python wsgi mod:yum install httpd mod_wsgi,其他系统类似,自己网上找包名安装即可。
添加配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Listen 8080 ## 如果不注释掉/etc/httpd/conf/httpd.conf里面的Listen 80,则会监听80和8080这2个端口 WSGIDaemonProcess helloapp processes=1 threads=2 display-name=%{GROUP} WSGIProcessGroup helloapp WSGIApplicationGroup %{GLOBAL} WSGISocketPrefix run/wsgi WSGIScriptAlias / /var/www/wsgi/app.wsgi ### 注意目录权限,apache用户要能访问 <Directory /var/www/wsgi> Options All AllowOverride All Require all granted </Directory> |
记得删除hello.py中最后一行run(***)。
重启Apache服务即可浏览器访问(查看服务状态可以看到1699 (wsgi:helloapp) -DFOREGROUND这个helloapp的wsgi服务已经运行)。访问方法跟上面一样,注意端口号改为8080。
uWSGI托管
参考文档:https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html
安装uwsgi:curl http://uwsgi.it/install | bash -s default /var/www/wsgi/uwsgi
运行uwsgi(注意使用绝对路径,否则app.wsgi中的dirname会报错):/var/www/wsgi/uwsgi –http :9900 –wsgi-file /var/www/wsgi/app.wsgi –master
uwsgi命令有很多参数可用,参考官方文档即可,另外uwsgi还支持各种web服务容器如Apache、Nginx等,请参考官方文档:https://uwsgi-docs.readthedocs.io/en/latest/WebServers.html
访问方法跟上面一样,注意端口号改为9900。
Web Server的原理及高性能异步方案
这个问题也困扰了我很久,一直都想知道一个高性能、高并发的web server是怎么实现的,比如Apache httpd、Nginx,怎么做到并发连接数成千上万?
看完如下这几篇文章有点大概了解了: