8

I run Connexion/Flask app like this:

import connexion
from flask_cors import CORS
from flask import g

app = connexion.App(__name__, specification_dir='swagger_server/swagger/')
app.add_api('swagger.yaml')
CORS(app.app)
with app.app.app_context():
    g.foo = 'bar'
    q = g.get('foo') # THIS WORKS
    print('variable', q)
app.run(port=8088, use_reloader=False)

somewhere else in code:

from flask import abort, g, current_app

def batch(machine=None):  # noqa: E501
    try:
        app = current_app._get_current_object()
        with app.app_context:
            bq = g.get('foo', None) # DOES NOT WORK HERE
            print('variable:', bq)
        res = MYHandler(bq).batch(machine)
    except:
        abort(404)
    return res

This does not work - I am not able to pass variable ('bla') to second code example.

Any idea how to pass context variable correctly? Or how to pass a variable and use it globally for all Flask handlers?

I've tried this solution (which works): In first code section I'd add:

app.app.config['foo'] = 'bar'

and in second code section there would be:

bq = current_app.config.get('foo')

This solution does not use application context and I am not sure if it's a correct way.

Michal Špondr
  • 1,337
  • 2
  • 21
  • 44

1 Answers1

3

Use a factory function to create your app and initialize your application scoped variables there, too. Then assign these variables to current_app within the with app.app.app_context() block:

import connexion
from flask import current_app

def create_app():
    app = connexion.App(__name__, specification_dir='swagger_server/swagger/')
    app.add_api('swagger.yaml')
    foo = 'bar' # needs to be declared and initialized here
    with app.app.app_context():
        current_app.foo = foo

    return app

app = create_app()
app.run(port=8088, use_reloader=False)

Then access these variables in your handler as follows:

import connexion
from flask import current_app

def batch():
    with current_app.app_context():
        local_var = current_app.foo
        print(local_var)

    print(local_var)

def another_request():
    with current_app.app_context():
        local_var = current_app.foo
        print('still there: ' + local_var)