python - Flask、蓝图、current_app

标签 python flask jinja2

我正在尝试从蓝图(我将在模板中使用的函数)在 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/

相关文章:

python - 从单行列表理解中解包列表

python - 如何在 Mac OS X 上安装 rpy2

python:如何拥有一个属性和一个setter函数来检测值发生的所有变化

python - Flask session 和多个用户

javascript - 国际化怎么走?

javascript - 模板无法通过 flask 正确渲染

python - Jinja 嵌套渲染可变内容

python - Jinja 中是否有用于记录宏的官方格式?

python - 如何使用键参数(不是 cmp)以混合顺序对字符串的 2 元素元组进行排序

ansible - 为什么 Ansible 会评估这个变量,即使是在一个 false if block 内?