Skip to content

Instantly share code, notes, and snippets.

@miikka

miikka/app.py Secret

Created March 15, 2016 19:38
Show Gist options
  • Save miikka/28a7bd77574a00fcec8d to your computer and use it in GitHub Desktop.
Save miikka/28a7bd77574a00fcec8d to your computer and use it in GitHub Desktop.
Multitenant Flask-SQLAlchemy demo
from flask import Flask, g, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
class MultiTenantSQLAlchemy(SQLAlchemy):
def choose_tenant(self, bind_key):
if hasattr(g, 'tenant'):
raise RuntimeError('Switching tenant in the middle of the request.')
g.tenant = bind_key
def get_engine(self, app=None, bind=None):
if bind is None:
if not hasattr(g, 'tenant'):
raise RuntimeError('No tenant chosen.')
bind = g.tenant
return super().get_engine(app=app, bind=bind)
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_BINDS'] = {
'test1': 'sqlite:///test1.db',
'test2': 'sqlite:///test2.db'
}
db = MultiTenantSQLAlchemy(app)
@app.before_request
def before_request():
db.choose_tenant(request.args['tenant'])
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
@app.route("/")
def list_users():
return repr(list(User.query.all()))
@app.route("/add", methods=["POST"])
def add_user():
user = User(request.form['username'], request.form['email'])
db.session.add(user)
db.session.commit()
return redirect(url_for('list_users'))
if __name__ == "__main__":
app.run(debug=True)
Copy link

ghost commented May 19, 2017

it's useful but how could I use this with alembic to migrate database schema???

@mjspier
Copy link

mjspier commented Aug 7, 2018

Awesome. Thanks for this. This should be added to the Flask-SQLAlchemy documentation.

@SatiyaWP
Copy link

SatiyaWP commented Jan 6, 2020

very nice solution, but can it be used in Flask Restplus? because i have problem using it, my swagger ui do not appear
thanks sir

@prasadsrg
Copy link

very nice solution, please let me know how to add data migration for multi-tent application.

@mohankumaru
Copy link

How do you pass SSL certificate, for login here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment