首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >烧瓶将变量从应用程序主文件传递到蓝图。

烧瓶将变量从应用程序主文件传递到蓝图。
EN

Stack Overflow用户
提问于 2020-03-24 08:46:07
回答 1查看 1.6K关注 0票数 2

如何将变量从应用程序主文件传递给蓝图

假设我有下面的示例应用程序。

代码语言:javascript
复制
#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)
代码语言:javascript
复制
#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,这看上去并不优雅。

EN

回答 1

Stack Overflow用户

发布于 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']一样使用它。所以代码应该如下所示:

代码语言:javascript
复制
#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)

然后在蓝图里,你可以这样读

代码语言:javascript
复制
#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"

我认为这是使用配置变量的最佳方法。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60827552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档