如何从应用程序主文件将变量传递到蓝图
假设我有以下示例应用程序。
#app.py
from flask import Flask
from example_blueprint import example_blueprint
data_to_pass="Hurray, You passed me"
app = Flask(__name__)
app.register_blueprint(example_blueprint)
#Blueprint
from flask import Blueprint
example_blueprint = Blueprint('example_blueprint', __name__)
@example_blueprint.route('/')
def index():
return "This is an example app"
如何将data_to_pass
传递给蓝图?
是否有内置烧瓶?
我正在尝试避免导入整个app.py
文件...看起来并不优雅。
答案 0 :(得分:2)
如果它是配置变量,则可以在app.py
中添加app.config['data_to_pass']
,在blueprint.py
中添加from flask import current_app
,然后可以使用它current_app.config['data_to_pass']
。因此,代码应如下所示:
#app.py
from flask import Flask
from example_blueprint import example_blueprint
data_to_pass="Hurray, You passed me"
app = Flask(__name__)
app.config['data_to_pass'] = data_to_pass
app.register_blueprint(example_blueprint)
然后在蓝图中,您可以像这样阅读它
#Blueprint
from flask import Blueprint, current_app
example_blueprint = Blueprint('example_blueprint', __name__)
@example_blueprint.route('/')
def index():
data_to_pass = current_app.config['data_to_pass']
return "This is an example app"
这是我认为使用配置变量的最佳方法。