Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdatabase_common.py
More file actions
Latest commit
48 lines (42 loc) · 1.79 KB
/
Copy pathdatabase_common.py
File metadata and controls
48 lines (42 loc) · 1.79 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
# 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.
importos
importpsycopg2
importpsycopg2.extras
defget_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_nameandpasswordandhostanddatabase_name
ifenv_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:
raiseKeyError('Some necessary environment variable(s) are not defined')
defopen_database():
try:
connection_string=get_connection_string()
connection=psycopg2.connect(connection_string)
connection.autocommit=True
exceptpsycopg2.DatabaseErrorasexception:
print('Database connection problem')
raiseexception
returnconnection
defconnection_handler(function):
defwrapper(*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()
returnret_value
returnwrapper