本文介紹了Python WEB應用部署的實現方法,分享給大家,具體如下:
使用Apache模塊mod_wsgi運行Python WSGI應用
Flask應用是基于WSGI規范的,所以它可以運行在任何一個支持WSGI協議的Web應用服務器中,最常用的就是 Apache+mod_wsgi 的方式
Apache主配置文件是/etc/httpd/conf/httpd.conf
其他配置文件存儲在/etc/httpd/conf.d/目錄
安裝mod_wsgi
安裝httpd-devel
$ yum install httpd-devel$ rpm -ql httpd-devel
安裝mod__wsgi
$ yum install mod_wsgi
安裝完成之后, mod_wsgi.so 會在Apache的modules目錄中
在 httpd.conf 文件中添加以下內容
LoadModule wsgi_module modules/mod_wsgi.so
重啟Apache來啟用配置
$ sudo service httpd restart
測試mod_wsgi
在Apache的DocumentRoot根目錄下創建一個文件 test.wsgi
def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] 這里的函數 application 即為WSGI應用對象,它返回的值就是該應用收到請求后的響應。
然后,再打開Apache的配置文件httpd.conf,在其最后加上URL路徑映射:
WSGIScriptAlias /test /var/www/html/test.wsgi
測試 curl http://localhost/test
使用Python虛擬環境
virtualenv 是一個創建隔絕的Python環境的工具。virtualenv創建一個包含所有必要的可執行文件以及 pip 庫的文件夾,用來使用Python工程所需的包。
配置app.wsgi
activate_this = '/var/www/html/py3env/bin/activate_this.py'execfile(activate_this, dict(__file__=activate_this))from flask import Flaskapplication = Flask(__name__)import syssys.path.insert(0, '/var/www/flask_test')from app import app as application
我們的虛擬環境在目錄 /var/www/html 下,你可以在其 /bin 子目錄中找到啟用腳本 activate_this.py 。在WSGI應用的一開始執行它即可。
apache配置文件
<VirtualHost *:80> ServerName example.com WSGIScriptAlias / /var/www/html/app.wsgi <Directory /var/www/html> Require all granted </Directory></VirtualHost>!
使用Nginx+uWSGI運行Python WSGI應用
uWSGI是一個Web應用服務器,它具有應用服務器,代理,進程管理及應用監控等功能。雖然uWSGI本身就可以直接用來當Web服務器,但一般建議將其作為應用服務器配合Nginx一起使用,這樣可以更好的發揮Nginx在Web端的強大功能。
安裝uWSGI
$ pip install uwsgi
創建 server.py
from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return 'Hello World!'if __name__ == '__main__': app.run() 創建 uwsgi 配置文件 uwsgi.ini
[uwsgi]http=0.0.0.0:8080 #指定項目執行的端口號 chdir=/var/www/html/# 項目目錄wsgi-file=/var/www/html/server.py # 項目啟動文件目錄callable=app #指定應用對象,WSGI標準是"application"master=true #主進程(監控其他進程狀態,如果有進程死了,則重啟)touch-reload=/var/www/html/ #監聽的文件路徑,當要監聽的文件路徑下的文件發生變化的時候自動重新加載服務器。daemonize=uwsgi.log #日志文件stats = 127.0.0.1:9090 #在指定的地址上,開啟狀態服務vacuum = True # 當服務器退出的時候自動清理環境,# 多進程&多線程processes = 6threads = 2
啟動
uwsgi --ini uwsgi.ini # 啟動uwsgi --reload uwsgi.pid # 重啟uwsgi --stop uwsgi.pid # 關閉
配置Nginx
將uWSGI的HTTP端口監聽改為socket端口監聽
socket=127.0.0.1:8080
修改nginx配置文件nginx.conf
server { listen 80; server_name localhost 192.168.1.5; #root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8080; } Nginx會將收到的所有請求都轉發到 127.0.0.1:8080 端口上,即uWSGI服務器上。
這里有一個坑,由于Centos7 SElinux導致的權限問題,Nginx無法將請求轉發到uWSGI,我直接把它關掉了。
vi /etc/selinux/config
把 SELINUX=enforcing 改成 SELINUX=disabled
重啟nginx測試。
使用Python虛擬環境
[uwsgi]...virtualenv=/home/Smi1e/virtualenv
部署多個應用
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答