1.搭建環境
- 創建python虛擬號環境
python -m venv venv
- 激活虛擬環境
source venv/bin/activate
(如果需要退出虛擬環境,執行:deactivate
)
- 安裝flask、uwsgi
pip install uwsgi flask
2. 通過原生方式啟動flask
- 創建一個應用
vim ~/myporject/app.py
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/hello')
def hello():
return jsonify({'message': 'Hello, World!'})
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000)
- 運行測試
python app.py
* Serving Flask app 'app'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on all addresses (0.0.0.0)
* Running on http://127.0.0.1:5000
* Running on http://192.168.0.129:5000
Press CTRL+C to quit
127.0.0.1 - - [25/May/2023 19:24:43] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [25/May/2023 19:24:47] "GET /hello HTTP/1.1" 200 -
正常情況下會在http://127.0.0.1:5000/hello中看到{"message":"Hello, World!"}
如果是要在外網訪問則需要修改服務商的安全組,在入向規則中添加5000端口
3.通過uWSGI啟動flask
- 創建一個文件夾
mkdir uwsgi
- 創建uWsgi配置文件
vim uwsgi.ini
,并填充以下內容:
[uwsgi]
chdir=~/myporject
http=0.0.0.0:5000
stats=%(chdir)/uwsgi/uwsgi.status
pidfile=%(chdir)/uwsgi/uwsgi.pid
wsgi-file=%(chdir)/app.py
callable=app
processes=2
threads=2
buffer-size=65536
- 通過uWSGI啟動
uwsgi --ini uwsgi.ini
服務啟動后會在uwsgi文件夾中生成.pid和.status文件,其中.pid里記錄了uWSGI服務的進程id,所以停止服務的指令為:
uwsgi --stop uwsgi/uwsgi.pid
- 查看uWSGI運行狀態
uwsgi --connect-and-read uwsgi/uwsgi.status
4.為uWSGI添加開機自啟動
- 創建啟動、停止腳本
vim start.sh
#!/bin/sh
~/myproject/venv/bin/uwsgi --ini ~/myproject/uwsgi.ini
vim stop.sh
#!/bin/sh
~/myproject/venv/bin/uwsgi --stop ~/myproject/uwsgi/uwsgi.pid
chmod a+x start.sh stop.sh
(增加執行權限)
- 配置啟動服務(文件名uwsgi對應的就是后續操作開啟、結束服務的名字,可以自定義)
vim /etc/systemd/system/uwsgi.service
[Unit]
Description=uWSGI instance
After=network.target remote-fs.target nss-lookup.target
[Service]
ExecStart=~/myproject/run.sh
ExecStop=~/myproject/stop.sh
[Install]
WantedBy=multi-user.target
如果發現有環境變量取不到,可以添加一個環境變量文件
[Service]
EnvironmentFile=path to your env file
...
env文件格式:
key1=value1
key2=value2
- 啟動服務,并開啟自啟動
sudo systemctl start uwsgi
sudo systemctl enable uwsgi
另一種啟動服務方式
service uwsig start
每次修改啟動服務的配置文件后需要執行systemctl daemon-reload
讓其生效
- 其他常用指令:
停止開機自啟動 : systemctl disable uwsgi
啟動 uwsgi 服務 : systemctl start uwsgi
停止 uwsgi 服務 : systemctl stop uwsgi
重啟 uwsgi 服務 : systemctl restart nginx
查看服務當前狀態 : systemctl status uwsgi
查看所有已啟動的服務 : systemctl list-units --type=service