Skip to content

Instantly share code, notes, and snippets.

@jlavelle
Last active July 26, 2018 19:58
Show Gist options
  • Select an option

  • Save jlavelle/2a2b7e921ce972dd2c70 to your computer and use it in GitHub Desktop.

Select an option

Save jlavelle/2a2b7e921ce972dd2c70 to your computer and use it in GitHub Desktop.

Revisions

  1. jlavelle revised this gist Mar 18, 2016. 1 changed file with 10 additions and 7 deletions.
    17 changes: 10 additions & 7 deletions flask_sqlalchemy_secondary_db_reflection.py
    Original file line number Diff line number Diff line change
    @@ -12,14 +12,17 @@
    # Create a Flask-SQLAlchemy bind for the second database
    SQLALCHEMY_BINDS = {'db2': os.environ.get('DATABASE_2_URI')}

    # Create an engine for the db2 bind, get it's metadata and reflect
    engine = db.get_engine(app, bind='db2')
    # Need to give SQLAlchemy object the current app context
    with app.app_context():
    # Create an engine for the db2 bind
    engine = db.get_engine(app, bind='db2')

    # Create a new session using the db2-bound engine. This is a Flask-SQLAlchemy
    # SignallingSession and should behave the same way as db.session (have not tested yet but docs say it will)
    Session = db.create_scoped_session({'bind': engine})
    db2_session = Session()

    meta = MetaData(engine)
    reflected_table = Table('table_to_reflect', meta, autoload=True, autoload_with=engine)

    # Create a new session using the db2-bound engine. This is a Flask-SQLAlchemy
    # SignallingSession and should behave the same way as db.session (have not tested yet but docs say it will)
    Session = db.create_scoped_session({'bind': engine})
    db2_session = Session()

    db2_session.query(reflected_table).first() # etc...
  2. jlavelle created this gist Mar 18, 2016.
    25 changes: 25 additions & 0 deletions flask_sqlalchemy_secondary_db_reflection.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    import os
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from sqlalchemy import MetaData, Table

    app = Flask()
    db = SQLAlchemy()
    db.init_app(app)

    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_1_URI')

    # Create a Flask-SQLAlchemy bind for the second database
    SQLALCHEMY_BINDS = {'db2': os.environ.get('DATABASE_2_URI')}

    # Create an engine for the db2 bind, get it's metadata and reflect
    engine = db.get_engine(app, bind='db2')
    meta = MetaData(engine)
    reflected_table = Table('table_to_reflect', meta, autoload=True, autoload_with=engine)

    # Create a new session using the db2-bound engine. This is a Flask-SQLAlchemy
    # SignallingSession and should behave the same way as db.session (have not tested yet but docs say it will)
    Session = db.create_scoped_session({'bind': engine})
    db2_session = Session()

    db2_session.query(reflected_table).first() # etc...