Flask:如何在另一个蓝图中使用一个蓝图中的 context_processor

nav*_*een 3 python flask

我在蓝图苹果中创建了一个 context_process ,

苹果>views.py

@apple.context_processor
def eat_apple():
    return dict(fruit='apple')
Run Code Online (Sandbox Code Playgroud)

如果我在另一个蓝图中,我将如何访问@apple.context_processor,以便在渲染模板时可以使用该变量?

Ken*_*der 7

不要将其分配给蓝图,而是将其分配给应用程序。

@app.context_processor
def eat_apple():
    return dict(fruit='apple')
Run Code Online (Sandbox Code Playgroud)

拥有蓝图本地上下文处理器的全部意义在于它仅在该蓝图上运行因此,如果这不是您想要的,请将其放在应用程序上。


use*_*983 7

您可以使用 Bluepint.app_context_processor

例如

bp = Blueprint("myblueprint", __name__, url_prefix=None)                               

@myblueprint.app_context_processor                                                        
def inject_template_globals():                                                   
    company = Company.query.first()                                              
    return dict(company=company)
Run Code Online (Sandbox Code Playgroud)