如何在烧瓶中使用g.user全局 [英] How to use g.user global in flask
问题描述
据我了解Flask中的g变量,它应该为我提供一个全局的地方来存放数据,例如登录后保存当前用户。这是正确的吗?
我想我的导航显示我的用户的名字,一旦登录,整个网站。
我的视图包含来自Flask的
import g #among other things
在登录期间,我分配
user = User。 query.filter_by(username = form.username.data).first()
if validate(user):
session ['logged_in'] = True
g.user = user
我似乎无法访问g.user。相反,当我的base.html模板具有以下...
< ul class =nav>
{%if session ['logged_in']%}
< li class =inactive>以{{g.user.username}}登录< / li>
{%endif%}
< / ul>
我得到错误:
jinja2.exceptions.UndefinedError
UndefinedError:'flask.ctx._RequestGlobals对象'没有属性'user'
登录不会正常工作。我缺少什么?
g
是一个线程本地,并按请求(请参阅关于代理的说明)。 会话
也是本地线程,但是在默认情况下,持久化到MAC签名的cookie并发送到客户端。
您遇到的问题是每个请求都重建 session
(因为它被发送到客户端,客户端发回给我们),而设置在 g
上的数据仅适用于这个请求的生命周期。
最简单的事情(注意
simple!= secure
- 如果你需要安全的话看看 Flask-Login )是简单地将用户的ID添加到会话中,并在每个请求上加载用户: @ app.before_request
def load_user():
if session [user_id]:
user = User.query.filter_by(username = session [user_id])。first()
else:
user = {name:Guest}#使用匿名方法用户改为
gu ser = user
As I understand the g variable in Flask, it should provide me with a global place to stash data like holding the current user after login. Is this correct?
I would like my navigation to display my user's name, once logged in, across the site.
My views contain
from Flask import g #among other things
During login, I assign
user = User.query.filter_by(username = form.username.data).first()
if validate(user):
session['logged_in'] = True
g.user = user
It doesn't seem I can access g.user. Instead, when my base.html template has the following...
<ul class="nav">
{% if session['logged_in'] %}
<li class="inactive">logged in as {{ g.user.username }}</li>
{% endif %}
</ul>
I get the error:
jinja2.exceptions.UndefinedError
UndefinedError: 'flask.ctx._RequestGlobals object' has no attribute 'user'
The login otherwise works fine. What am I missing?
g
is a thread local and is per-request (See A Note On Proxies). The session
is also a thread local, but in the default context is persisted to a MAC-signed cookie and sent to the client.
The problem that you are running into is that session
is rebuilt on each request (since it is sent to the client and the client sends it back to us), while data set on g
is only available for the lifetime of this request.
The simplest thing to do (note simple != secure
- if you need secure take a look at Flask-Login) is to simply add the user's ID to the session and load the user on each request:
@app.before_request
def load_user():
if session["user_id"]:
user = User.query.filter_by(username=session["user_id"]).first()
else:
user = {"name": "Guest"} # Make it better, use an anonymous User instead
g.user = user
这篇关于如何在烧瓶中使用g.user全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!