任何 Web 程序如果要正式上線,都需要使用 Web Server, 也就是 Web 服務器。通常 Python 模塊和庫自帶的 Web 運行程序都只是用于開發和測試。而 Python 產品的正式運行環境可以選擇 Apache 和Nginx 作為 Web Server。
Apache 和 Nginx 默認只能處理靜態文件,如果讓它們處理 Python 腳本呢?官方給出的答案就是?WSGI。
WSGi是一種通用API協議,用于在底層Web服務器和Python Web應用之間進行映射。
示例運行環境介紹:
Ubuntu 18.04.1 LTS
Python 2.7.15rc1
Apache 2.4.29
在 Ubuntu 系統安裝 apache 的 wsgi 模塊。
sudo apt install libapache2-mod-wsgi-py3
重啟 Apache
sudo apachectl restart
或者
sudo service apache2 restart
創建一個簡單的 WSGI 程序,保存到/www/wsgi/myapp.wsgi:
nano /www/wsgi/myapp.wsgi
myapp.wsgi 內容:
def application(environ, start_response):
? ? status = '200 OK'
? ? output = b'Hello World!'
? ??response_headers = [('Content-type', 'text/plain'),? ('Content-Length', str(len(output)))]
? ???start_response(status, response_headers)
? ? return [output]
需要注意的是:mod_wsgi? 需要入口程序被命名為application, 除非你通過額外的mod_wsgi? 配置來指定它使用其他名字。
加載myapp.wsgi, 修改/etc/apache2/sites-enabled/000-default.conf
sudo nano 000-default.conf
添加內容:
WSGIScriptAlias /myapp /www/wsgi/myapp.wsgi
<Directory /www/wsgi>
Require all granted
</Directory>
真實案例:
重啟apache ,查看效果:
sudo service apache2 restart
打開瀏覽器:http://192.168.23.39/myapp
成功!