LoginSignup
3
4

More than 5 years have passed since last update.

環境変数を使ってPythonからPostgresSQLに接続する

Posted at

久しぶりにやって時間を費やしてしまったのでメモ✍️

手順:
1. 環境変数を.bash_profile に設定
2. Pythonのプログラムを作成
3. Pythonを実行

1. 環境変数を.bash_profile に設定

以下のルールに従って記述

$HOME/.bash_profile
export DATABASE_URL="postgres://username:password@hostname:5432/database"

具体例

$HOME/.bash_profile
export DATABASE_URL="postgres://hiroaki:password123@my-database.abc123defg.us-east-1.rds.amazonaws.com:5432/postgres"

2.Pythonのプログラムを作成

こんな感じのソースになります

getConn.py
import os
import psycopg2
import urllib.parse


def getConn():
    urllib.parse.uses_netloc.append("postgres")
    url = urllib.parse.urlparse(os.environ["DATABASE_URL"])
    conn = psycopg2.connect(
        database=url.path[1:],
        user=url.username,
        password=url.password,
        host=url.hostname,
        port=url.port
    )
    return conn

3. Pythonを実行

.bash_profileを編集する前から開いてたターミナルで作業するときは、

$ source ~/.bash_profile

を忘れずに。

3
4
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
3
4