Question

I have an application that is constructed as follows:

app = Flask(__name__)

app.wsgi_app = DispatcherMiddleware(frontend.create_app(), {
    '/api': api.create_app()
})

app.config['DATABASE'] = db

I want to access the same database in both the frontend and api apps, but when I run something like current_app.config['DATABASE'] in Blueprints registered to api, that raises KeyError: 'DATABASE'. Is it possible to inherit configurations so that tests, etc. need only modify the top-level abstraction? Thanks.

Was it helpful?

Solution

Simply change your create_app methods on frontend and api to take a configuration dictionary and use flask.Config to create a configuration with all the properties of app.config (loadable from environmental variables, etc.):

from flask import Config
from werkzeug.wsgi import DispatcherMiddlware

config = Config()
config.from_envvar("YOUR_PROGRAM_CONFIG")

app = DispatcherMiddlware(frontend.create_app(config), {
    '/api': api.create_app(config)
})

Then you can merge the provided config with each of your app's configurations:

def create_app(config):
    app = Flask(__name__)
    app.config.update(config)

    # Potentially, load another config
    app.config.from_envvar("YOUR_PROGRAM_CONFIG_FRONTEND", silent=True)

    return app

Note that there is no need to create an app to route to other apps - the dispatcher middleware can already do that for you.

Also note that if you are already using blueprints it may make more sense to simply ship the blueprints and compose them on a single application, rather than using dispatcher middleware (depending, of course on how complex your apps are).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top