【问题标题】:Flask, Blueprint, current_app烧瓶、蓝图、current_app
【发布时间】:2012-03-30 15:37:10
【问题描述】:

我正在尝试从蓝图(我将在模板中使用的函数)在 Jinja 环境中添加一个函数。

Main.py

app = Flask(__name__)
app.register_blueprint(heysyni)

MyBluePrint.py

heysyni = Blueprint('heysyni', __name__)
@heysyni.route('/heysyni'):
    return render_template('heysyni.html', heysini=res_heysini)

现在在 MyBluePrint.py 中,我想添加如下内容:

def role_function():
    return 'admin'

app.jinja_env.globals.update(role_function=role_function)

然后我就可以在我的模板中使用这个功能了。我不知道如何访问该应用程序,因为

app = current_app._get_current_object()

返回错误:

working outside of request context

我怎样才能实现这样的模式?

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    消息错误实际上很清楚:

    在请求上下文之外工作

    在我的蓝图中,我试图让我的应用程序超出“请求”功能:

    heysyni = Blueprint('heysyni', __name__)
    
    app = current_app._get_current_object()
    print(app)
    
    @heysyni.route('/heysyni/')
    def aheysyni():
        return 'hello'
    

    我只需要将 current_app 语句移到函数中。最后它是这样工作的:

    Main.py

    from flask import Flask
    from Ablueprint import heysyni
    
    app = Flask(__name__)
    app.register_blueprint(heysyni)
    
    @app.route("/")
    def hello():
        return "Hello World!"
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    Ablueprint.py

    from flask import Blueprint, current_app
    
    heysyni = Blueprint('heysyni', __name__)
    
    @heysyni.route('/heysyni/')
    def aheysyni():
        # Got my app here
        app = current_app._get_current_object()
        return 'hello'
    

    【讨论】:

    • 但是current_app可以直接在函数中使用,为什么要使用_get_current_object()?
    猜你喜欢
    • 2012-09-27
    • 2012-06-16
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多