-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathconnection.py
More file actions
74 lines (57 loc) · 2.39 KB
/
connection.py
File metadata and controls
74 lines (57 loc) · 2.39 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import csv
import os
import psycopg2
import psycopg2.extras
def csv_to_dict(file_path):
with open(file_path, 'r', newline='') as f:
reader = csv.DictReader(f)
database = [dict(row) for row in reader]
return database
def dict_to_csv(file_path, data, is_answers=False):
with open(file_path, 'w', newline='') as f:
writer = csv.DictWriter(f, ANSWER_DATA_HEADER if is_answers else QUESTION_DATA_HEADER)
writer.writeheader()
writer.writerows(data)
def append_to_csv(file_path, data):
with open(file_path, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerows([data.values()])
# Creates a decorator to handle the database connection/cursor opening/closing.
# Creates the cursor with RealDictCursor, thus it returns real dictionaries, where the column names are the keys.
def get_connection_string():
# setup connection string
# to do this, please define these environment variables first
user_name = os.environ.get('PSQL_USER_NAME')
password = os.environ.get('PSQL_PASSWORD')
host = os.environ.get('PSQL_HOST')
database_name = os.environ.get('PSQL_DB_NAME')
env_variables_defined = user_name and password and host and database_name
if env_variables_defined:
# this string describes all info for psycopg2 to connect to the database
return 'postgresql://{user_name}:{password}@{host}/{database_name}'.format(
user_name=user_name,
password=password,
host=host,
database_name=database_name
)
else:
raise KeyError('Some necessary environment variable(s) are not defined')
def open_database():
try:
connection_string = get_connection_string()
connection = psycopg2.connect(connection_string)
connection.autocommit = True
except psycopg2.DatabaseError as exception:
print('Database connection problem')
raise exception
return connection
def connection_handler(function):
def wrapper(*args, **kwargs):
connection = open_database()
# we set the cursor_factory parameter to return with a RealDictCursor cursor (cursor which provide dictionaries)
dict_cur = connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
ret_value = function(dict_cur, *args, **kwargs)
dict_cur.close()
connection.close()
return ret_value
return wrapper