Flask,blue_print,current_app

gpa*_*sse 7 python jinja2 flask

我试图从蓝图(我将用于模板的函数)在jinja环境中添加一个函数.

Main.py

app = Flask(__name__)
app.register_blueprint(heysyni)
Run Code Online (Sandbox Code Playgroud)

MyBluePrint.py

heysyni = Blueprint('heysyni', __name__)
@heysyni.route('/heysyni'):
    return render_template('heysyni.html',heysini=res_heysini)
Run Code Online (Sandbox Code Playgroud)

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

def role_function():
    return 'admin'
app.jinja_env.globals.update(role_function=role_function)
Run Code Online (Sandbox Code Playgroud)

然后我将能够在我的模板中使用此功能.从那时起我无法弄清楚如何访问该应用程序

app = current_app._get_current_object()
Run Code Online (Sandbox Code Playgroud)

返回错误

working outside of request context
Run Code Online (Sandbox Code Playgroud)

我该如何实现这样的模式?

gpa*_*sse 9

消息错误实际上非常清楚:

在请求上下文之外工作

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

heysyni = Blueprint('heysyni', __name__)

app = current_app._get_current_object()
print app

@heysyni.route('/heysyni/')
def aheysyni():
    return 'hello'
Run Code Online (Sandbox Code Playgroud)

我只是添加将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)
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)