たなしょのメモ

日々勉強していることをつらつらと

開発環境構築(vagrant、postgresql、pythonでアプリをつくる)その2

python3のインストール

vagrantにpython3をインストールする。
公式のサイトを参照していればインストール。

www.python.jp

flaskのインストール

pip3でflaskをインストールすると下記警告とエラーが出た。

$ sudo pip3 install flask
WARNING: The directory '/home/vagrant/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/flask/
Could not fetch URL https://pypi.org/simple/flask/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/flask/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping
ERROR: Could not find a version that satisfies the requirement flask (from versions: none)
ERROR: No matching distribution found for flask
WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.")) - skipping

解決策がなくてモヤモヤしていたが下記方法を試したら無事インストールできた(python2の力を使っているけど本当に大丈夫?)。
1. python-pipのインストール

sudo apt-get install python-pip

2.pipによるインストール

sudo pip install flask

pip listを実行したところをflaskがあったのでひとまずOK!

vscodeでvargrant内のファイルを修正できるようにする

vscodevagrant内のファイルを修正できるとなにかと便利なのでssh file systemsを使って設定する。
1. Vagrantfileのあるディレクトリでvagrant ssh-configコマンドを入力して各種ステータスを確認する。 2. 上記ステータスをssh-fsのセッテイング画面でhost(hostname)、port、username、private keyに設定する。
(rootは特に決まっていなかったので/home/vagrantを設定した)

Flaskを試す

下記ソースコードを実行してflaskが起動するか試す。

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    name = "Hello world"
    return name

@app.route('/good')
def good():
    name = "good"
    return name

if __name__ == "__main__":
    app.run(debug=True)

実行してみるとネットワークが見つからない。どうも入力するIPが見つからないために起こっているらしい。
この記事に対処法があったので試してみる。

yuk.hatenablog.com

Vagrantfileの下記コメントアウトを外す。

config.vm.network :private_network, ip: "192.168.33.10"

hello.pyを下記のように変更した。

app.run(host='0.0.0.0')

http://192.168.33.10:5000/にアクセスしたら無事hello worldが表示された。

pythonからpostgreSQLに接続してデータを取得する

postgresに接続するためにpsycopg2というモジュールが必要なので下記コマンドを使ってインストールする。

sudo apt-get install python-psycopg2
sudo apt-get install libpq-dev

テーブルをレコードから取得するソースコードを書いた。

import psycopg2

users = 'USERNAME'
db = 'DBNAME'
password = 'PASSWORD'
conn = psycopg2.connect(" user=" + users + " dbname=" + db + " password=" + password)

cur = conn.cursor()
cur.execute('select * from menu;')
results = cur.fetchall()

print(results)

cur.close()
conn.close()

実行するとエラーが出てしまった。

$ python postgres_dataget.py
Traceback (most recent call last):
  File "postgres_dataget.py", line 6, in <module>
    conn = psycopg2.connect(" user=" + users + " dbname=" + db + " password=" + password)
  File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
    connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL:  password authentication failed for user "postgres"

どうも調べたら下記のようにすると問題ないらしい。
1. sudo -u postgres psqlでログインする。
2. ALTER USER postgres PASSWORD 'my_postgres_password'; を設定する。
3. pg_hba.confを下記のように変更する。

$ sudo diff /etc/postgresql/9.3/main/pg_hba.conf_bk /etc/postgresql/9.3/main/pg_hba.conf
85c85
< local   all             postgres                                peer
---
> local   all             postgres                                md5
  1. service postgresql restartで再起動する。

これでやってみると

$ python postgres_dataget.py
[(1, '\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88\xe5\xbc\x81\xe5\xbd\x93', 400, 400)]

実行できた。でも日本語表示のところが\xe3などになっているのが少し気になる。

from flask import Flask
import psycopg2

app = Flask(__name__)

@app.route('/')
def hello():
    uusers = 'USERNAME'
    db = 'DBNAME'
    password = 'PASSWORD'
    conn = psycopg2.connect(" user=" + users + " dbname=" + db + " password=" + password)

    cur = conn.cursor()
    cur.execute('select * from menu;')
    results = cur.fetchall()

    cur.close()
    conn.close()

    return results[0][1]
    
if __name__ == "__main__":
    app.run(host='0.0.0.0')

上記のコードを起動したところ無事\xeになっていたところが日本語で表示された良かった。