Python

Python/WSGI应用快速入门实战

话题 [ 上一页 | 下一页 ]
########################################################################################
#CentOS8 Linux下Python/WSGI应用快速入门实战,作者:Warren.Zhou 上海释锐教育软件有限公司#
########################################################################################
 
#login as warren user(not root user)
 
#make a new directory
mkdir python_web_server
cd python_web_server
 
##############
#01.安装uWSGI#
##############
#pip3 uninstall uwsgi
sudo yum install pcre pcre-devel pcre-static
pip3 install uwsgi -I --no-cache-dir --user
 
 
###################
#02.第一个WSGI应用#
###################
vi my_first_wsgi_application.py
# my_first_wsgi_application.py:the first WSGI application
def application(environ, start_response):
  status = '200 OK'
  output = b'Hello World!\nThis is my_first_wsgi_application.py\n'
  response_headers = [('Content-type', 'text/plain'),('Content-Length', str(len(output)))]
  start_response(status, response_headers)
  return [output]
 
###########################
#03.将其部署在HTTP端口8080#
###########################
sudo firewall-cmd --query-port=8080/tcp
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
sudo firewall-cmd --reload
uwsgi --http :8080 --wsgi-file my_first_wsgi_application.py --master --processes 4 --threads 2
 
#################################################
#04.将WSGI应用放在一个完整的web服务器(Nginx)之后#
#################################################
sudo yum install nginx
sudo service nginx start
sudo vi /etc/nginx/nginx.conf
location / {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:3031;
}
sudo nginx -s reload
 
#################################################################################################
#05.将运行选项"--http :8080"改成"--socket 127.0.0.1:3031",本地从原来的http协议改成使用uwsgi协议#
#################################################################################################
uwsgi --socket 127.0.0.1:3031 --wsgi-file my_first_wsgi_application.py --master --processes 4 --threads 2 --py-autoreload 1 --stats 127.0.0.1:9191
 
#################################################
#06.部署Flask(Flask是一个流行的Python web微框架)#
#################################################
pip3 install --upgrade virtualenv --user
virtualenv -p python3.6 $HOME/.env
pip3 install flask --user
 
####################
#07.第一个Flask应用#
####################
vi my_first_flask_app.py
# my_first_flask_app.app
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route("/world")
def helloWorld():
    return "Hello World"

@app.route("/")
def default():
    #return redirect(url_for('helloWorld'))
    return "Welcome to threeoa uwsgi server , this is the first <span style='color:red'>Flask</span> app."

@app.route("/ai")
def helloAi():
    return "Hello AI"

@app.route("/post/<int:post_id>")
def show_post(post_id):
    return 'Post %d' % post_id

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
 
#####################################
#08.唯一新增"--callable app"运行选项#
#####################################
uwsgi --socket 127.0.0.1:3031 --wsgi-file my_first_flask_app.py --processes 4 --threads 2  --py-autoreload 1 --stats 127.0.0.1:9191 --callable app
 
#################################################
#09.部署Django(Django是最常使用的Python web框架)#
#################################################
PENDING...
 
##################################
#10.创建uwsgi.ini运行选项配置文件#
##################################
vi uwsgi.ini
[uwsgi]
#工程目录
chdir=/home/warren/python_web_server
# python虚拟环境目录
home=/home/warren/.env 
# 启动flask应用的文件名,不用加.py
module=my_first_flask_app  
# 应用名,与my_first_flask_app.py文件中一致
callable=app 
master=true
# worker的进程个数
processes=4
threads=2 
chmod-socket=666
logfile-chmod=644
# uwsgi的进程名称前缀,启动后可通过ps -ef | grep FirstFlask查找到这个进程
procname-prefix-spaced=FirstFlask 
#py文件修改,自动加载,也就是设置热启动了
py-autoreload=1  
vacuum=true 
# 退出uwsgi是否清理中间文件,包含pid、sock和status文件
# socket监听端口和文件,配置nginx时候使用
socket=127.0.0.1:3031
socket=%(chdir)/auto_generated_files/uwsgi.sock 
# status文件,可以查看uwsgi的运行状态
stats=%(chdir)/auto_generated_files/uwsgi.status 
# pid文件,通过该文件可以控制uwsgi的重启和停止
pidfile=%(chdir)/auto_generated_files/uwsgi.pid 
# 设置后台模式,然后将日志输出到uwsgi.log。当调试时,可先注释掉此内容
daemonize=%(chdir)/auto_generated_files/uwsgi.log
#http监听端口,测试时使用
#http=:8080
 
############################
#11.start/reload/stop uwsgi#
############################
mkdir auto_generated_files
uwsgi --ini uwsgi.ini
uwsgi --reload auto_generated_files/uwsgi.pid
uwsgi --stop auto_generated_files/uwsgi.pid
 
#####################
#12.测试运行是否正常#
#####################
Windows Browser: http://192.168.1.51:8080/ 输出效果如下:
nginx-uwsgi-flask-1
Linux Command Line: curl get http://192.168.1.51:8080/ 输出效果如下:
nginx-uwsgi-flask-curl
 
 
#####################################################################
#13.系统重启后自动运行(centos8不建议用rc.local,推荐采用systemd技术)#
#####################################################################
 
#nginx
vi /lib/systemd/system/nginx.service
[Unit]

Description=The nginx HTTP and reverse proxy server

After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target
#execute this command,create symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service
systemctl enable nginx.service
 
#uwsgi
vi /etc/init.d/uwsgid.sh
#!/bin/bash
if [ ! -n "$1" ];then
    echo "Usages: sh uwsgid.sh [start|stop|restart]"
    exit 0
fi

if [ $1 = start ];then
    psid=`ps aux | grep "uwsgi" | grep -v "grep" | wc -l` 
    if [[ $psid -gt 4 ]];then
        echo "uwsgi is running!"
        exit 0 
    else
      /usr/local/bin/uwsgi --ini /home/warren/python_web_server/uwsgi.ini
      echo "Start uwsgi service [OK]"
    fi
    # nginx call uwsgi:13: Permission denied
    setsebool httpd_can_network_connect=1
    echo "setsebool httpd_can_network_connect=1 [OK]"
elif [ $1 = stop ];then
    killall -9 uwsgi
    echo "Stop uwsgi service [OK]"
elif [ $1 = restart ];then
    killall -9 uwsgi
    /usr/local/bin/uwsgi --ini /home/warren/python_web_server/uwsgi.ini
    echo "Restart uwsgi service [OK]"
else
    echo "Usages: sh uwsgid.sh [start|stop|restart]"
fi
 
# mark uwsgid.sh with executable permission
chmod +x /etc/init.d/uwsgid.sh
 
# add uwsgi.service
vi /lib/systemd/system/uwsgi.service
[Unit]
Description=uWSGId
After=network.target

[Service]
User=warren
Group=warren
Type=forking
ExecStart=/etc/init.d/uwsgid.sh start
ExecReload=/etc/init.d/uwsgid.sh restart
ExecStop=/etc/init.d/uwsgid.sh stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
 
# mark uwsgi.service with executable permission
chmod +x  /lib/systemd/system/uwsgi.service
 
# execute this command,created symlink /etc/systemd/system/uwsgi.service → /lib/systemd/system/uwsgi.service
systemctl enable /lib/systemd/system/uwsgi.service #开机自启
systemctl start uwsgid.service
systemctl restart uwsgid.service
systemctl stop uwsgid.service
 
转载请注明出处“文章作者:Warren.Zhou 上海释锐教育软件有限公司”
0 (0 票)

最近公司&教育行业新闻 最近公司&教育行业新闻

• 释锐2020版教育信息化系统建设方案正式发布

• 公司创始人周清华先生被“上海曹鹏音乐中心”授予“2019年度积极奉献 先进个人”称号

• 延期开学后,孩子“宅家”咋学习?教育部:利用网络平台,“停课不停学”