-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
32 lines (29 loc) · 889 Bytes
/
utils.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
import sqlalchemy
from contextlib import contextmanager
from sqlalchemy.orm import sessionmaker
def create_sql_engine(database_name):
'''
Create sqlalchemy engine for postgres database
@param database_name: str, name of database
@return: sqlalchemy engine
'''
return sqlalchemy.create_engine('postgresql://localhost/' + database_name,
echo = False,
connect_args = {"host": '/var/run/postgresql/'})
@contextmanager
def session_scope(engine):
'''
Create a sqlalchemy session and close it when finished
@param engine: sqlalchemy engine
@return: None
'''
Session = sessionmaker(bind=engine)
session = Session()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()