Source code for accre.database.engine
"""
SQLAclhemy engine object for connecting to the
ACCRE database
"""
import ssl
from sqlalchemy import create_engine
from accre.config import get_config
CONFIG = get_config()
_default_engine = None
[docs]def create_admin_engine():
"""
Return an sqlalchemy Engine object to connect to the ACCRE admin
database.
:returns: Engine for the ACCRE admin database
:rtype: sqlalchemy.engine.Engine
"""
ssl_context = None
cafile= CONFIG['admin-db'].get('cacert', '/accre/ca/ca.vampire.crt')
if CONFIG['admin-db'].get('ssl', 'true').lower() == 'true':
ssl_context = ssl.SSLContext()
ssl_context.load_verify_locations(cafile=cafile)
conn_str = '{0}://{1}:{2}@{3}:{4}/{5}'.format(
CONFIG['admin-db']['driver'],
CONFIG['admin-db']['user'],
CONFIG['admin-db']['password'],
CONFIG['admin-db']['host'],
CONFIG['admin-db']['port'],
CONFIG['admin-db']['database']
)
return create_engine(conn_str, connect_args={'ssl_context': ssl_context})
[docs]def get_default_engine():
"""
The SQLAlchemy engine should generally persist over the application
lifetime and can be safely reused between client objects. This
helper function provides the admin engine if it has already been
instantiated or creates it if not.
"""
global _default_engine
if _default_engine is None:
_default_engine = create_admin_engine()
return _default_engine
[docs]def set_default_engine(engine):
"""
There is need to set a default engine in case an engine has already been registered
from a different context. For example: during testing: setup might create the db client using an engine,
any other dbclient accesses after that must happen through the same engine
Args:
engine: database engine
Returns:
None
"""
global _default_engine
_default_engine = engine