在 Flask 中,我想了解如何创建一个行为类似于 current_user
的函数,因为它在任何地方( Controller 和 View )都可用,但我很难真正知道它是什么搜索以找到答案。
我能找到的关于 SO 的最接近的帖子是 this one, but it's for Ruby而不是 Python,有人能指出我正确的方向吗?谢谢!
我目前拥有的:
在我的 __main__.py
中我有这个:
@app.context_processor
def foo_processor():
def foo():
return 'Hello World'
这样做的结果是我可以在我的 Jinja 模板中访问 {{ foo }}
而无需从我的 Controller 发送它。不幸的是,我无法在我的 Controller 中访问 foo within
,而这正是我希望也能够做到的。我是否需要以某种方式导入它,如果需要,如何导入?
最佳答案
如果我理解正确,您需要一个可以在模板和 Controller 中使用的变量,而不必每次都将其传递到模板中。为此,首先,创建一个函数来获取变量。这可能类似于获取用户设置。然后在上下文处理器中,传递此函数的结果。要在您的 Controller 中也访问它,请创建一个附加变量来保存 getter 的值。请注意,如果函数返回不同的值,您可能需要调用函数而不是使用变量。
# create a getter function, this returns the property's value.
def get_property():
return "Test Text"
property = get_property() # this is only to make code pretty later on.
# the context processor passes the property to the templates.
@app.context_processor
def property_processor():
return dict(property=get_property())
在您的 Controller 中,您可以访问之前创建的变量。
def view():
if property == true:
return redirect(url_for('index'))
else:
return redirect(url_for('access_denied'))
请注意,如果您的值会发生变化,您可能需要改用该函数并在每次呈现 View 时调用 getter。这会将第一个 if
语句改为 if get_property() == true:
。
关于python - 如何创建类似于 current_user 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65047812/