Flask:如何在蓝图中使用应用程序上下文?

时间:2016-09-29 11:55:51

标签: design-patterns flask

我正在学习烧瓶和蟒蛇,并且无法围绕典型烧瓶应用程序需要构建的方式。

我需要从内部蓝图访问应用配置。像这样的东西

#blueprint.py
from flask import Blueprint

sample_blueprint = Blueprint("sample", __name__)

# defining a route for this blueprint
@sample_blueprint.route("/")
def index():
     # !this is the problematic line
     # need to access some config from the app
     x = app.config["SOMETHING"]
     # how to access app inside blueprint?

如果在蓝图中导入app是解决方案,这不会导致循环导入吗?即在应用程序中导入蓝图,在蓝图中导入应用程序?

2 个答案:

答案 0 :(得分:3)

来自appcontext的文档:

  

应用程序上下文支持 current_app 上下文本地

应用于您的示例:

document.getElementById('go').onclick = function () {

var limit = document.getElementById('limit').value;

var total = 0;

for (i = 0; i <= limit; i ++) {

    total = total + i;



};
document.getElementById('total').value = total;
};

这里有一个小gist的参考,如评论中所述。

答案 1 :(得分:0)

在您的应用中-注册蓝图时-您需要手动推送上下文。

请参考下面的代码片段,并注意对init_db函数的调用是如何与应用程序上下文一起包装的-with可确保在完成任务后销毁该上下文。

def create_app():
    app = Flask(__name__)

    with app.app_context():
        init_db()

    return app

Source

相关问题