Python 如何在 jinja 2 中访问会话变量 - Flask
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42013067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access session variables in jinja 2 - Flask
提问by bpb101
Do I need to pass session variables manually from Flask to my HTML or are they automatically sent in some way?
我需要手动将会话变量从 Flask 传递到我的 HTML 还是它们以某种方式自动发送?
Can I do
我可不可以做
return render_template('index.html')
and access a session variable username
, for example, like {{session['username'}}
in the HTML file?
并访问会话变量username
,例如{{session['username'}}
在 HTML 文件中?
回答by bpb101
In python
在蟒蛇中
session['username'] = 'username'
in jinja2 you can go
在 jinja2 你可以去
{{session['username']}}
回答by chikwapuro
If you want to isolate certain parts of your HTML using session you can call the session directly on those elements:
如果您想使用 session 隔离 HTML 的某些部分,您可以直接在这些元素上调用 session:
{% if session['username'] %}
<li>Logout</li>
{% endif %}
回答by user10257507
@bpb101 is correct on the Jinja2 format (though left out the spaces as others have mentioned). In the HTML/Jinja2 template you can simply call the session
dictionary without passing it to the template:
@bpb101 在 Jinja2 格式上是正确的(尽管省略了其他人提到的空格)。在 HTML/Jinja2 模板中,您可以简单地调用session
字典而不将其传递给模板:
{{ session['username'] }}
However the other example, in the Python code, would actually overwrite the value of session['username']
with the string 'username'
, due to variable assignment. If you were trying to set a variable to the value of session['username']
you would use:
然而,由于变量赋值,Python 代码中的另一个示例实际上会session['username']
用 string覆盖 的值'username'
。如果您尝试将变量设置为session['username']
您将使用的值:
username = session['username']
Otherwise if you just needed to test or use the value for some other reason you can access it directly for example:
否则,如果您只是出于其他原因需要测试或使用该值,则可以直接访问它,例如:
if session['username'] == some_value:
return "The username is", session['username']
Hopefully that helps for anyone new to Flask or Jinja2 that might wonder why their session variables are being overwritten.
希望这对 Flask 或 Jinja2 的新手有所帮助,他们可能想知道为什么他们的会话变量会被覆盖。