-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata_manager.py
More file actions
54 lines (45 loc) · 1.87 KB
/
Copy pathdata_manager.py
File metadata and controls
54 lines (45 loc) · 1.87 KB
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
45
46
47
48
49
50
51
52
53
54
import os
import psycopg2
import psycopg2.extras
def establish_connection(connection_data=None):
"""
Create a database connection based on the :connection_data: parameter
:connection_data: Connection string attributes
:returns: psycopg2.connection
"""
if connection_data is None:
connection_data = get_connection_data()
try:
connect_str = "dbname={} user={} host={} password={}".format(connection_data['dbname'],
connection_data['user'],
connection_data['host'],
connection_data['password'])
# connect_str = os.environ.get('DATABASE_URL')
conn = psycopg2.connect(connect_str)
conn.autocommit = True
except psycopg2.DatabaseError as e:
print("Cannot connect to database.")
print(e)
else:
return conn
def get_connection_data(db_name=None):
"""
Give back a properly formatted dictionary based on the environment variables values which are started
with :MY__PSQL_: prefix
:db_name: optional parameter. By default, it uses the environment variable value.
"""
if db_name is None:
db_name = os.environ.get('MY_PSQL_DBNAME')
return {
'dbname': db_name,
'user': os.environ.get('MY_PSQL_USER'),
'host': os.environ.get('MY_PSQL_HOST'),
'password': os.environ.get('MY_PSQL_PASSWORD')
}
def execute_select(statement, variables=None, fetchall=True):
result_set = []
with establish_connection() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cursor:
cursor.execute(statement, variables)
result_set = cursor.fetchall() if fetchall else cursor.fetchone()
return result_set