gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:45:32 25 4
gpt4 key购买 nike

我像这样运行 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)

代码中的其他地方:

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

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

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

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

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

在第二个代码部分将有:

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

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

最佳答案

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

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)

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

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)

关于python - 如何将变量传递到 Connexion Flask 应用程序上下文中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53941243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com