Ubuntu 16.04
Sponsored Link

Python + mod_wsgi2016/06/13

 
mod_wsgi (WSGI : Web Server Gateway Interface) をインストールして、Python スクリプトの実行を高速化します。
[1] mod_wsgi をインストールします。
root@www:~#
apt-get -y install libapache2-mod-wsgi
[2] 例として、/var/www/html/test_wsgi.py が /test_wsgi でアクセスできるよう設定します。
root@www:~#
vi /etc/apache2/conf-available/wsgi.conf
# 新規作成

WSGIScriptAlias /test_wsgi /var/www/html/test_wsgi.py
root@www:~#
a2enconf wsgi

Enabling conf wsgi.
To activate the new configuration, you need to run:
service apache2 reload
root@www:~#
systemctl restart apache2
[3] [2] で設定したテストスクリプトを作成して動作確認します。
root@www:~#
vi /var/www/html/test_wsgi.py
# 新規作成

def application(environ,start_response):
    status = '200 OK'
    html = '<html>\n' \
           '<body>\n' \
           '<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">\n' \
           'mod_wsgi Test Page\n' \
           '</div>\n' \
           '</body>\n' \
           '</html>\n'
    response_header = [('Content-type','text/html')]
    start_response(status,response_header)
    return [html]
[4] Django を利用する場合は以下のように設定します。( Django 環境の構築はこちらを参照 )
例として、「ubuntu」ユーザー所有「/home/ubuntu/venv/testproject」配下の「testapp」を動作させるよう設定します。
設定後はテストページにアクセスして動作確認してください。
root@www:~#
vi /etc/apache2/conf-available/django.conf
# 新規作成

WSGIDaemonProcess testapp python-path=/home/ubuntu/venv/testproject:/home/ubuntu/venv/lib/python2.7/site-packages
WSGIProcessGroup testapp
WSGIScriptAlias /django /home/ubuntu/venv/testproject/testproject/wsgi.py

<Directory /home/ubuntu/venv/testproject>
    Require all granted
</Directory>
root@www:~#
a2enconf django

Enabling conf django.
To activate the new configuration, you need to run:
service apache2 reload
root@www:~#
systemctl restart apache2
関連コンテンツ