前提条件
項目名 | 内容 |
---|---|
mac | macOS High Sierra 10.13.6 |
docker | 18.06.1 |
os | centos 7 |
Docker起動
- CentOSのイメージをダウンロード
docker pull centos:7
docker run -itd --privileged -p 80:80 -p 443:443 --name app -v {ローカルディレレクトリ}:/share centos:latest /sbin/init
※localeにja_JP.utf8を追加する場合「/etc/yum.conf」の「override_install_langs」を”en_US.utf8,ja_JP.utf8”に変更して「yum -y reinstall glibc-common」
Unable to find image 'centos:latest' locally
latest: Pulling from library/centos
Digest: sha256:6f6d986d425aeabdc3a02cb61c02abb2e78e57357e92417d6d58332856024faf
Status: Downloaded newer image for centos:latest
> docker exec -it app /bin/bash
Python開発環境構築
1. pythonをインストール
sudo easy_install python
2. 以下をダウンロードしてpipをインストール
python get-pip.py
3. Django導入
sudo pip install django
4. pythonのAPIモジュール作成(nginx + uwsgi+ flsk + sqlalchemy) ※CentOS7
4.1 各種必要なモジュールのインストール
yum install epel-release
yum install python python-devel python2-pip gcc nginx
sudo pip install --upgrade pip
sudo pip install flask SQLAlchemy flask-sqlalchemy PyMySQL psycopg2 uwsgi
4.2 nginxの設定変更
pythonモジュールを格納するディレクトリを作成(※仮・・・本運用では格納先を考える必要あり)
mkdir /usr/share/nginx/html/flask
4.3 nginxの設定
location / {
include uwsgi_params;
uwsgi_pass unix:///usr/share/nginx/html/flask/tmp/uwsgi.sock;
}
4.4 uwsgiの設定
ディレクトリ作成
mkdir /usr/share/nginx/html/flask/tmp
chown nginx. /usr/share/nginx/html/flask/tmp
iniファイル作成
/usr/share/nginx/html/flask/sample.ini
[uwsgi]
module = app
callable = app
master = true
processes = 1
socket = tmp/uwsgi.sock
chmod-socket = 666
vacuum = true
die-on-term = true
サンプルファイル作成
/usr/share/nginx/html/flask/app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!!"
if __name__ == "__main__":
app.run()
4.5 起動
nginxの起動
nginx -t
systemctl start nginx
uwsgiの起動
cd /usr/share/nginx/html/flask/
uwsgi --ini sample.ini
4.6 ブラウザにアクセス
http://localhost/ にアクセスして「Hello World!!」が表示されていれば成功。
5 Python+Postgres
5.1 postgresqlインストール、sampleデータ登録
yum install postgresql postgresql-devel postgresql-server
su -
systemctl start postgresql.service
su - postgres
initdb --encoding=UTF8 --no-locale
createuser sample
psql
postgres=# select * from pg_user;
postgres=# \q
createdb sample --o sample
psql
postgres=# \l
postgres=CTc/postgres
postgres=# \q
psql -U sample -d sample
sample=> create table sample
sample-> (id CHAR(4) NOT NULL,name TEXT NOT NULL,PRIMARY KEY (id));
sample-> insert INTO sample VALUES ( 1,'hoge');
5.2 pythonライブラリインストール
yum install python-psycopg2
python -c 'import psycopg2'
5.3 その他
pythonで文字コード関係でエラーが出る場合
先頭に以下をつける
# coding:utf-8
vimの設定を以下の通りにする
set encoding=utf-8