Commit a8934514 authored by Lars Kruse's avatar Lars Kruse
Browse files

fix(database): use the request-based database sessions provided by flask-sqlalchemy

Currently the database session is created during application startup and
is used in all threads.  This is problematic, since the session is not
thread-safe.
Now we use the request-based database session provided by
flask-sqlachemy instead.

But this does not really solve the problem of using the same session in
different threads, since the threads are started within a request.
parent 0a675430
Pipeline #1183 passed with stage
in 1 minute and 22 seconds
......@@ -34,6 +34,7 @@ from flask_sqlalchemy import SQLAlchemy
from src.base.logger import AuraLogger
from src.base.config import AuraConfig
from src.base.utils import SimpleUtil as SU
from src.scheduling.models import DB
config = AuraConfig()
......@@ -45,7 +46,7 @@ def configure_flask():
# FIXME Instantiate SQLAlchemy without the need for Flask
app = Flask(__name__)
configure_flask()
DB = SQLAlchemy(app)
DB.set_flask_db(SQLAlchemy(app))
class EngineRunner:
......
......@@ -41,12 +41,32 @@ engine = sa.create_engine(config.get_database_uri())
Base = declarative_base()
Base.metadata.bind = engine
class DB():
session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)
session = Session()
class DB:
Model = Base
@classmethod
def set_flask_db(cls, db):
"""configure an "flask_sqlalchemy.SQLAlchemy" object for future usage via 'DB.session'
The SQLAlchemy object should be created once during startup (`SQLAlchemy(flask_app)`).
It provides a request-based database session, which can be accessed via 'DB.session'.
"""
cls._flask_db = db
@classmethod
@property
def session(cls):
"""return the database session provided for this request"""
try:
flask_db = cls._flask_db
except AttributeError:
raise RuntimeError(
"Missing configuration of application database (provided by flask-sqlalchemy)."
" You need to run `DB.set_flask_db(...)` during startup."
)
else:
return flask_db.session
class AuraDatabaseModel():
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment