【问题标题】:Flask: How to use app context inside blueprints?Flask:如何在蓝图中使用应用程序上下文?
【发布时间】:2020-08-13 00:04:24
【问题描述】:

我正在学习烧瓶和 python,但我无法理解典型烧瓶应用程序需要构建的方式。

我需要从蓝图中访问应用配置。像这样的

#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?

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

【问题讨论】:

    标签: design-patterns flask


    【解决方案1】:

    来自关于appcontext的文档:

    应用程序上下文是 current_app 本地上下文

    的动力

    应用于您的示例:

    from flask import Blueprint, current_app
    
    sample = Blueprint('sample', __name__)
    
    @sample.route('/')
    def index():
        x = current_app.config['SOMETHING']
    

    这里是我整理的一个小gist供参考,在cmets中有提到。

    【讨论】:

    • 我无法使用 current_app,因为它说没有应用程序上下文。也许我没有做对。我会尝试看看是否可以按照您提到的方式进行。
    • 如果我们将蓝图拆分为单独的文件,current_app 在蓝图中对我不起作用。对我来说,蓝图必须在一个单独的文件中,而应用程序必须在一个单独的文件中。
    • 要点给了我一个 404
    • 以上代码结果为RuntimeError: Working outside of application context.。要修复,我必须将访问配置的代码包装在以下内容中:with current_app.app_context:
    【解决方案2】:

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

    请参阅下面的 sn-p 并注意 init_db 函数的调用如何与应用程序上下文一起包装 - with 确保在您的任务完成后上下文被销毁。

    def create_app():
        app = Flask(__name__)
    
        with app.app_context():
            init_db()
    
        return app
    

    Source

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2017-06-17
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多