Multiple Database
Menyetel Multiple Koneksi ke database secara dinamis sesuai dengan domain yang request

SQLALCHEMY_BINDS = os.environ.get('DATABASE_URL_MULTI')
import ast from flask import request connection_map = ast.literal_eval(os.environ.get('DATABASE_URL_MULTI')) @app.before_request def before_request(): origin = request.headers.get('Origin') if origin: origin = origin.replace('http://', '').replace('https://', '').replace('/', '') # print(f'ORIGIN: {origin}') if origin in connection_map.keys(): db.choose_connection(origin) else: db.choose_connection('default') else: db.choose_connection('default')
from flask import g class MultiTenantSQLAlchemy(SQLAlchemy): def choose_connection(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 Connection chosen.') bind = g.tenant return super().get_engine(app=app, bind=bind) db = MultiTenantSQLAlchemy() # db = SQLAlchemy()
import ast import os app.config['SQLALCHEMY_BINDS'] = ast.literal_eval(os.environ.get('DATABASE_URL_MULTI'))
Last updated