如何将变量传递到 Connexion Flask 应用程序上下文中?

Mic*_*ndr 8 python flask connexion

我像这样运行 Connexion/Flask 应用程序:

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)
Run Code Online (Sandbox Code Playgroud)

代码中的其他地方:

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
Run Code Online (Sandbox Code Playgroud)

这不起作用 - 我无法将变量('bla')传递给第二个代码示例。

知道如何正确传递上下文变量吗?或者如何传递一个变量并在所有 Flask 处理程序中全局使用它?

我已经尝试过这个解决方案(有效):在第一个代码部分我会添加:

app.app.config['foo'] = 'bar'
Run Code Online (Sandbox Code Playgroud)

在第二个代码部分将有:

bq = current_app.config.get('foo')
Run Code Online (Sandbox Code Playgroud)

此解决方案不使用应用程序上下文,我不确定它是否是正确的方法。

小智 3

使用工厂函数来创建应用程序并在那里初始化应用程序范围的变量。然后将这些变量分配给块current_appwith app.app.app_context()

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)
Run Code Online (Sandbox Code Playgroud)

然后在处理程序中访问这些变量,如下所示:

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)

Run Code Online (Sandbox Code Playgroud)