I have two Flask apps running with a domain dispatcher (based on this guide).
I'd like to share my models between the apps. Is it safe to have the SQLAlchemy
object in a shared location and just call db.init_app
with both applications?
This is my project structure:
app_one/
├ __init__.py
├ database/
│ ├ __init__.py
│ └ models.py
└ ...
app_two/
├ __init__.py
├ database/
│ ├ __init__.py
│ └ models.py
└ ...
shared/
└ ...
dispatcher.py
This is dispatcher.py
:
from flask import Flask
import app_one
import app_two
class Dispatcher:
def __init__(self, config_file, app_one_config_file, app_two_config_file):
self.app_one = app_one.create_app(config_file, app_one_config_file)
self.app_two = app_two.create_app(config_file, app_two_config_file)
def __call__(self, environ, start_response):
host = environ['HTTP_HOST']
if host == 'app_two_domain.com':
return self.app_two(environ, start_response)
return self.app_one(environ, start_response)
def create_app(*args, **kwargs):
app = Flask(__name__)
app.wsgi_app = Dispatcher(*args, **kwargs)
return app
Currently both app_one/database/__init__.py
and app_two/database/__init__.py
contain:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy
And in both create_app
functions:
from .database import db
db.init_app(app)
I'd like to move db
into shared/database/__init__.py
, and then either:
call
init_app
with both apps, ormake
Dispatcher
a subclass ofFlask
, callinit_app
inDispatcher
, and then register the Flask-SQLAlchemy extension with both apps withapp.extensions['sqlalchemy'] = _SQLAlchemyState(db)
.
What's the right way to go about this? (Splitting app_one
and app_two
isn't an option.)
(Note: this is not a duplicate of this question, since both of my apps are Flask apps.)