Flask+SQLAlchemy with multiple dababases and shared models

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

database_uris = ['sqlite:///a.sqlite', 'sqlite:///b.sqlite']

engines = [create_engine(uri, convert_unicode=True) for uri in database_uris]
scoped_sessions = [scoped_session(sessionmaker(engine)) for engine in engines]

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    email = Column(String(120), unique=True)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from flask import Flask, g, request

app = Flask(__name__)

@app.before_request
def select_database():
    try:
        g.db = scoped_sessions[int(request.args['db'])]
    except (ValueError, KeyError):
        g.db = scoped_sessions[0]


@app.teardown_appcontext
def shutdown_session(exception=None):
    g.db.remove()


@app.route('/')
def index():
    return str(g.db.query(User).all())

if __name__=='__main__':
    app.run(debug=True)
Created (last updated )
Comments powered by Disqus