Pass another object to the main flask application

Take a look at application factories, which should do what you're looking for. You'd create a factory that returned your Flask app that you'd send the logger to - something like this:

def create_app(logger_instance):
    app = Flask(__name__)
    app.config['LOGGER'] = logger_instance
    return app

And then in your runserver.py, you'd create and pass in the logger:

from yourapp import create_app
if __name__ == '__main__':
    logger = MyProcess()
    app = create_app(logger)
    app.run()

Once that's done, your app can refer to the logger inside app.config['LOGGER'].


You might want to use flask app context for this

from flask import _app_ctx_stack 

def getLogger():
    appContext = _app_ctx_stack.top
    logger = getattr(appContext, "Logger", None)
    if logger is None:
        logger = MyProcess()
        appContext.Logger = logger
    return logger

....

@app.route('/nb_trendy')
def nb_trendy():
    logger = getLogger()
    res = logger.get_trendy()
    return jsonify(res)

more insight from Armin on that: https://speakerdeck.com/mitsuhiko/advanced-flask-patterns

Tags:

Python

Flask