如何从Flask中的方法路由中访问context_processor



我希望在不污染before_request装饰器中的请求对象的情况下,设置可用于视图和方法的变量。

上下文处理器似乎是一种很好的方法,但是,我不知道如何从我的方法中实际访问它们。

我想出的最好的解决方案是对上下文函数进行记忆,这样它就不会被调用两次,一次是我在方法中调用的,另一次是Flask将其注入模板时调用的。

然而,这将为所有未来的请求缓存该方法,我只希望每个请求都缓存它。

这是我的工作示例

from functools import cache
@app.context_processor
@cache
def setup_context():
return {
'planet': db.query('select planet from planets order by random()').first() 
}
@app.route("/")
def index():
ctx = setup_context()
if ctx['planet'] == 'pluto':
return redirect('/pluto-is-not-a-planet')
return render_template('planet_greeting.html')

关于如何在不使用functools.che的情况下实现这一点,有什么想法吗?

可能有一种更优雅的方法可以做到这一点,但以下是我迄今为止所想到的。

基本思想是使用扩展模式并创建一个对象";当前";应用程序传递给的。

然后,我可以使用该对象上的属性来访问_app_ctx_stack,并使用context_processor钩子用上下文变量填充模板。

这种方法将允许我拥有不使用";g";在我的路线上是一个很好的合作对象。

from flask import (
Flask, current_app, _app_ctx_stack,
render_template as template
)
from random import shuffle
planets = ['earth', 'pluto', 'mars']
class Current(object):
def __init__(self, app=None):
self.app = app
self.app.context_processor(self.context_processor)

def context_processor(self):
return _app_ctx_stack.top.__dict__
@property
def planet(self):
ctx = _app_ctx_stack.top
if not hasattr(ctx, 'planet'):
shuffle(planets)
ctx.planet = {
'name': planets[0]
}
return ctx.planet
app = Flask(__name__)
current = Current(app)
@app.route("/")
def index():
if current.planet['name'] == 'pluto':
return "Pluto is not a planet!"
return template("planet.html")

if __name__ == '__main__':
app.run(debug=True)

在我的模板中

{%# in my template %}
The planet is {{ planet.name }}!

最新更新