如何将变量从应用程序主文件传递给蓝图
假设我有下面的示例应用程序。
#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 file...it,这看上去并不优雅。
发布于 2020-03-24 08:52:41
如果它是一个配置变量,那么您可以在您的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"我认为这是使用配置变量的最佳方法。
https://stackoverflow.com/questions/60827552
复制相似问题