Flask SQLAlchemy setup dynamic URI Flask SQLAlchemy setup dynamic URI flask flask

Flask SQLAlchemy setup dynamic URI


You can make a custom builder for the session that will re-create the engine and scoped session when your rules dictate it. Something like

class SessionManager(object):    def __init__(self):        self.session = None    def get_session(self):        # return existing session or make a new engine and scoped_session

To make this class transparent, use Werkzeug's LocalProxy. The code that uses the sessions won't have to change at all.

session_manager = SessionManager()db_session = LocalProxy(session_manager.get_session)