介绍
类似于,nginx 结合 php-fpm 可以支持跳转到 php 程序一样,nginx 后端也可以挂 uwsgi 来用 python 程序作为server端。
参考文档
《一个UWSGI的例子》:https://blog.csdn.net/crazyhacking/article/details/18617873
主要是关于flask + python 的代码开发例子。
《uWSGI+Nginx+Flask在Linux下的部署》https://www.cnblogs.com/zhangjpn/p/6876412.html?utm_source=itdadao&utm_medium=referral
主要是关于部署
软件安装
pip install uwsgi
yum install python-flask
yum install nginx
配置
nginx 配置
使用 http/http-socket 协议
server {
listen 80 default_server;
server_name _;
location ~ /pptserver {
proxy_pass http://127.0.0.1:8888;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
使用unix socket 协议(本地文件)
server {
listen 80 default_server;
server_name _;
location ~ /pptserver {
include uwsgi_params;
uwsgi_pass unix://tmp/ppt.sock;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
注意,要确保 sock 文件可以被访问,一般设置为 777 即可。
uwsgi 配置
cat /data/install/conf/uwsgi.conf
[uwsgi]
## For directlly http access
http-socket=127.0.0.1:8888
### For nginx proxy
#socket=/tmp/ppt.sock
wsgi-file=/data/install/bin/pptserver.py
#plugins = python
callable = app
#chdir = /data/install/bin
touch-reload=/data/install/bin/
processes = 2
threads = 2
stats = 127.0.0.1:9191
post-buffering = 8192
buffer-size = 65535
socket-timeout = 10
uid = apache
gid = apache
master = true
#protocol = uwsgi
注意:使用 http或者socket协议时,只需要切换下(socket或者http)即可。
运行程序
启动 nginx
service nginx restart
启动 uwsgi
/usr/bin/uwsgi --ini /data/install/conf/uwsgi.conf
测试
# curl "localhost/pptserver?uid=3434&name=get_jingle" -d "name=post_jigang"
{"get_name":"get_jingle","post_name":"post_jigang"}
附件
pptserver.py
# cat /data/install/bin/pptserver.py
from flask import Flask,render_template, jsonify
from flask import request
app = Flask(__name__)
@app.route('/pptserver', methods=['GET', 'POST'])
#def index():
def index():
requester = request.remote_addr
#logging.info('Data request from: %s' % requester)
url = request.url
uid = url.split('uid=')[-1]
get_name=request.args.get("name")
post_name=request.form.get("name")
#return "Test message, your input uid=%s, method=%s, get_name=%s, post_name=%s from %s\n" % (uid, request.method, get_name, post_name, requester)
return jsonify(get_name=get_name,post_name=post_name)
if __name__ == '__main__':
app.run()
git 工程
参考我的 git 示例工程
https://github.com/duanjigang1983/study