Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable into Connexion Flask app context?

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.

like image 489
Michal Špondr Avatar asked Dec 27 '18 07:12

Michal Špondr


People also ask

How do you send context in Flask?

Flask automatically pushes an application context when handling a request. View functions, error handlers, and other functions that run during a request will have access to current_app . Flask will also automatically push an app context when running CLI commands registered with Flask.

How do I fix RuntimeError working outside of request context?

RuntimeError: Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem. This should typically only happen when testing code that expects an active request.

Can you have global variables in Flask?

More often than not, what you're really trying to do, when you use global variables in Flask, is to save user entered or recorded information across different routes, while concurrently allowing for modifications to the same. As it happens, Flask has an inbuilt library for this functionality : Flask Sessions.

What is app_context in Flask?

app_context() call when you run similar functions in your views. The reason is that Flask already handles the management of the application context for you when it is handling actual web requests.


1 Answers

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)

like image 196
Olof Kohlhaas Avatar answered Nov 15 '22 08:11

Olof Kohlhaas