Ubuntu 14.04 + Apache 2.4 + Python 3.5.1 で Flask動作環境を構築する

OSインストール直後の状態からflaskの動作確認まで。

環境

コマンド実行

# use japan mirror server
sudo sed -i'~' -E "s@http://(..\.)?(archive|security)\.ubuntu\.com/ubuntu@http://ftp.jaist.ac.jp/pub/Linux/ubuntu@g" /etc/apt/sources.list

# update installed package
sudo apt upgrade
sudo apt update

# install apache2
sudo apt install apache2

# install python 3.5.1
sudo apt install -y build-essential
sudo apt-get -y build-dep python3.4
mkdir downloads
cd downloads
wget https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
tar -zxvf Python-3.5.1.tgz
cd Python-3.5.1
./configure --enable-shared --prefix=/opt/python-3.5.1
make
sudo make install
echo "/opt/python-3.5.1/lib" | sudo tee /etc/ld.so.conf
sudo /sbin/ldconfig

# create virtualenv & install mod_wsgi
cd ~
/opt/python-3.5.1/bin/python3 -m venv example-env
. example-env/bin/activate
pip install -U pip
pip install mod_wsgi-httpd
pip install mod_wsgi

# install flask
pip install flask

ファイル作成

/etc/apache2/mods-available/wsgi_express.conf

WSGIPythonHome /home/vagrant/example-env
WSGISocketPrefix /var/run/wsgi

/etc/apache2/mods-available/wsgi_express.load

LoadModule wsgi_module /home/vagrant/example-env/lib/python3.5/site-packages/mod_wsgi_packages/httpd/modules/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so

/etc/apache2/sites-available/example-site.conf

<VirtualHost *:80>

    WSGIDaemonProcess example-site user=www-data group=www-data threads=5 python-path=/home/vagrant/example-env/lib/python3.5/site-packages
    WSGIScriptAlias / /var/www/example-site/app.wsgi
    WSGIScriptReloading On

    <Directory /var/www/example-site>
        WSGIProcessGroup example-site
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

/var/www/example-site/app.py

# -*- coding:utf-8 -*-
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'completed!'

if __name__ == '__main__':
    app.run()

/var/www/example-site/app.wsgi

import sys, os
sys.path.append('/var/www/example-site')

from app import app as application

コマンド実行

sudo a2enmod wsgi_express
sudo a2dissite 000-default
sudo a2ensite example-site
sudo service apache2 reload

テスト

ブラウザに completed! と表示されればOK

参考