title: Flask-SQLAlchemy - on the fly connections to multiple databases
body: <p>I have a <code>flask webapp</code> where users will be able to connect to their own mysql databases and query their own tables</p>
  
  <p>What's the best way to create multiple connections (to different databases) using flask-sqlalchemy. It seems like it needs to be done with <code>scoped_session</code> and <code>sessionmaker</code> but cant seem to wrap my head around it.</p>
  
  <p>Also the second part of the question, once I create a connection to a mysql db for one of the users, how do i persist the connection across requests ?</p>
  
  <p>Currently, i put the connection string for each user on the flask session variable and at each new request, i create the engine and connection as such</p>
  
  <pre><code>engine = create_engine(connection_string, convert_unicode=True)
  conn = engine.connect()
  db_session = Session(bind=conn) # Session - i create it globally on the __init__ like this Session = scoped_session(sessionmaker()) and import it in the view
  
  ## Query using the db_session
  </code></pre>
  
  <p>This seems super wasteful to create the engine and the connection with every request - cant the connection be persisted across requests ? </p>