我正在尝试从蓝图(我将在模板中使用的函数)在 Jinja 环境中添加一个函数。
主.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
我怎样才能实现这样的模式?
最佳答案
消息错误其实很清楚:
working outside of request context
在我的蓝图中,我试图让我的应用程序脱离“请求”功能:
heysyni = Blueprint('heysyni', __name__)
app = current_app._get_current_object()
print(app)
@heysyni.route('/heysyni/')
def aheysyni():
return 'hello'
我只需要将 current_app 语句移动到函数中即可。最后它以这种方式工作:
主.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'
关于python - Flask、蓝图、current_app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9946136/