Last active
July 26, 2018 19:58
-
-
Save jlavelle/2a2b7e921ce972dd2c70 to your computer and use it in GitHub Desktop.
An example of configuring a Flask-SQLAlchemy session for a relfected Table object from a legacy database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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')} | |
# 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) | |
db2_session.query(reflected_table).first() # etc... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment