How to access session variables in jinja 2 - Flask

后端 未结 3 1185
遇见更好的自我
遇见更好的自我 2020-12-14 20:20

Do I need to pass session variables manually from Flask to my HTML or are they automatically sent in some way?

Can I do

return render_template(\'inde         


        
3条回答
  •  死守一世寂寞
    2020-12-14 20:57

    @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:

    {{ 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:

    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.

提交回复
热议问题