-
-
Save miikka/28a7bd77574a00fcec8d to your computer and use it in GitHub Desktop.
Multitenant Flask-SQLAlchemy demo
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
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) |
Awesome. Thanks for this. This should be added to the Flask-SQLAlchemy documentation.
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
very nice solution, please let me know how to add data migration for multi-tent application.
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
it's useful but how could I use this with alembic to migrate database schema???