Python uWSGI 安裝配置

安全劍客發表於2019-12-25
主要介紹如何部署簡單的 WSGI 應用和常見的 Web 框架。

Python uWSGI 安裝配置Python uWSGI 安裝配置
以 Ubuntu/Debian 為例,先安裝依賴包:

apt-get install build-essential python-dev
Python 安裝 uWSGI

1、通過 pip  命令

pip install uwsgi

2、下載安裝 指令碼

curl http://uwsgi.it/install | bash -s default /tmp/uwsgi

將 uWSGI 二進位制安裝到 /tmp/uwsgi ,你可以修改它。

3、原始碼安裝:

wget http://projects.unbit.it/downloads/uwsgi-latest.tar.gz
tar zxvf uwsgi-latest.tar.gz
cd uwsgi-latest
make

安裝完成後,在當前目錄下,你會獲得一個 uwsgi 二進位制檔案。

第一個 WSGI 應用

讓我們從一個簡單的 "Hello World" 開始,建立檔案 foobar.py,程式碼如下:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

uWSGI Python 載入器將會搜尋的預設函式 application 。

接下來我們啟動 uWSGI 來執行一個 HTTP 伺服器,將程式部署在HTTP埠 9090 上:

uwsgi --http :9090 --wsgi-file foobar.py
新增併發和監控

預設情況下,uWSGI 啟動一個單一的程式和一個單一的執行緒。

你可以用 --processes 選項新增更多的程式,或者使用 --threads 選項新增更多的執行緒 ,也可以兩者同時使用。

uwsgi --http :9090 --wsgi-file foobar.py --master --processes 4 --threads 2

以上 命令將會生成 4 個程式, 每個程式有 2 個執行緒。

如果你要執行監控任務,可以使用 stats 子系統,監控的資料格式是 JSON:

uwsgi --http :9090 --wsgi-file foobar.py --master --processes 4 --threads 2 --stats 127.0.0.1:9191

我們可以安裝 uwsgitop(類似  Linux top 命令) 來檢視監控資料:

pip install uwsgitop
結合 Web 伺服器使用

我們可以將 uWSGI 和 Nginx Web 伺服器結合使用,實現更高的併發效能。

一個常用的nginx配置如下:

location / {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:3031;
}

以上程式碼表示使用 nginx 接收的 Web 請求傳遞給埠為 3031 的 uWSGI 服務來處理。

現在,我們可以生成 uWSGI 來本地使用 uwsgi 協議:

uwsgi --socket 127.0.0.1:3031 --wsgi-file foobar.py --master --processes 4 --threads 2 --stats 127.0.0.1:9191

如果你的 Web 伺服器使用 HTTP,那麼你必須告訴 uWSGI 本地使用 http 協議 (這與會自己生成一個代理的–http不同):

uwsgi --http-socket 127.0.0.1:3031 --wsgi-file foobar.py --master --processes 4 --threads 2 --stats 127.0.0.1:9191
部署 Django

Django 是最常使用的 Python web 框架,假設 Django 專案位於 /home/foobar/myproject:

uwsgi --socket 127.0.0.1:3031 --chdir /home/foobar/myproject/ --wsgi-file myproject/wsgi.py --master --processes 4 --threads 2 --stats 127.0.0.1:9191

--chdir 用於指定專案路徑。

我們可以把以上的命令弄成一個 yourfile.ini 配置檔案:

[uwsgi]
socket = 127.0.0.1:3031
chdir = /home/foobar/myproject/
wsgi-file = myproject/wsgi.py
processes = 4
threads = 2
stats = 127.0.0.1:9191

接下來你只需要執行以下命令即可:

uwsgi yourfile.ini
部署 Flask

Flask 是一個流行的 Python web 框架。

建立檔案 myflaskapp.py ,程式碼如下:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return "I am app 1"

執行以下命令:

uwsgi --socket 127.0.0.1:3031 --wsgi-file myflaskapp.py --callable app --processes 4 --threads 2 --stats 127.0.0.1:9191

原文地址: https://www.linuxprobe.com/python-uwsgi-installation.html

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31559985/viewspace-2670589/,如需轉載,請註明出處,否則將追究法律責任。

相關文章