LoginSignup
0
0

More than 3 years have passed since last update.

リモートのpython3(psycopg2)からubuntu16.04@AWSのpostgresqlに接続

Last updated at Posted at 2019-10-28

前提

①ubuntu16.04をAWS上で立ち上げpython3,postgresqlをインストール完了
②python3でpsyopg2が扱える

以下はSelectクエリの実行例です。リモートで実行する前にローカルで問題なく実行できることを確認しておきます。

#################################
###    Selectクエリの実行例    ###
#################################
import psycopg2, psycopg2.extras

# 1. Postgesqlの接続設定(設定に合わせて修正してください)
#HOST     = "localhost  #ローカルで実行するとき
HOST     = "172.0.0.1"  
PORT     = "5432"
DBNAME   = "postgres"
USER     = "postgres"
PASSWORD = "p@ssword"
CREDENTIAL = "host={h} port={p} dbname={db} user={u} password={pa}"\
    .format(h=HOST,p=PORT,db=DBNAME,u=USER,pa=PASSWORD)

QUERY = "Select * from exercise" #テーブル名は任意に設定してください


# 2. Postgresに接続してクエリを実行
with psycopg2.connect(CREDENTIAL) as conn:
    with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:

        # クエリ実行
        cur.execute(QUERY) 
        rows = cur.fetchall()

# 3. 結果を表示
print(rows[0])

やったこと

①セキュリティグループの設定(下図の赤枠の設定)

Postgresql_リモート.jpg
※「0.0.0.0/0」はすべてのリモートアクセスを許可しているので注意してください。

セキュリティグループの設定をする前にリモート接続を実行すると以下の通りTimeoutエラーが出ました。


OperationalError: could not connect to server: Connection timed out (0x0000274C/10060)
    Is the server running on host "【リモートIP】" and accepting
    TCP/IP connections on port 5432?

セキュリティグループの設定にPostgresqlを追加すると以下のRefusedエラーに代わりました。これでTCPの設定はOKです。

OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
    Is the server running on host "【リモートIP】" and accepting
    TCP/IP connections on port 5432?
②postgresqlの設定ファイルの修正とpostgresqlの再起動

ph_hba.conf と postgresql.confのファイルを修正します。そして修正後にpostgesqlを再起動するのですが以下のブログの最後の方で詳しく説明されていますのでこちらを参考ください。
https://qiita.com/ibara1454/items/40ce2d82926f48cf02bc

以上で終了です。ここまでの設定をすれば接続してクエリがリモートから実行できました。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0