如何一次将变量传递给所有路径?

2024-05-16 21:06:05 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我有一个Flask应用程序,我需要一个特定的用户传递到所有路由,因为应用程序中的所有页面都需要特定的用户来呈现模板。我不想像平常一样传递给用户

return render_template('index.html',user=user)

因为我必须对render_模板中的所有管线重复相同的操作。 请问我该怎么做


Tags: 用户模板应用程序flask路由indexreturnhtml
2条回答

如果要向所有路由/页面/模板发送变量。您可以在flask中使用会话

from flask import Flask,session
[...]
session['x'] = user

现在,您可以在代码中的任何地方使用它,使用session['x']

在模板中

{{session['x']}}

可以通过使用以下实现创建自定义渲染模板函数来执行此操作

from flask import render_template as real_render_template
from yourapp import user  # Import the user variable or set it

def render_template(*args, **kwargs):
    return real_render_template(*args, **kwargs, user=user)

也可以通过functools.partial完成:

from flask import render_template as real_render_template
from yourapp import user  # Import the user variable or set it
from functools import partial

render_template = partial(real_render_template, user=user)

相关问题 更多 >