-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsetup_postgres.py
More file actions
44 lines (34 loc) · 953 Bytes
/
setup_postgres.py
File metadata and controls
44 lines (34 loc) · 953 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import psycopg2
import psycopg2.extras as extras
from datetime import datetime
from contextlib import contextmanager
import os
from dotenv import load_dotenv
load_dotenv(".env")
port = os.environ.get("postgresql_port",None)
password = os.environ.get("postgresql_password",None)
creds = dict(
host = "localhost",
dbname = "connect_db",
user = "postgres",
password = password,
port = port
)
@contextmanager
def connect():
conn = None
ended = False
try:
with psycopg2.connect(**creds) as conn: #need this
with conn.cursor(cursor_factory=extras.DictCursor) as cur:
print(f"Successfully connected to PostgreSQL server at {datetime.now()}.")
yield conn, cur
except Exception as e:
print("Error:",e)
if conn is not None:
ended = conn.close()
#print("Closed connection in except block")
else:
ended = True
#print("Connection is",conn,"at end of function")
#print(cur)