-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.py
48 lines (40 loc) · 1.54 KB
/
connection.py
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
import os
import psycopg2
import psycopg2.extras
def get_connection_string():
# setup connection string
# to do this, please define these environment variables first
user_name = ('postgres')
password = ('Gz1996828')
host = ('localhost')
database_name =('askMate2')
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