如何在烧瓶中使用 g.user global [英] How to use g.user global in flask

查看:29
本文介绍了如何在烧瓶中使用 g.user global的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解 Flask 中的 g 变量,它应该为我提供一个全局位置来存储数据,例如在登录后保存当前用户.这是正确的吗?

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.

我的观点包含

from 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 模板具有以下内容时...

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>

我收到错误:

jinja2.exceptions.UndefinedError
UndefinedError: 'flask.ctx._RequestGlobals object' has no attribute 'user'

否则登录工作正常.我错过了什么?

The login otherwise works fine. What am I missing?

推荐答案

g 是一个 线程本地 并且是针对每个请求的(参见 A Note On Proxies).session 也是一个本地线程,但在默认上下文中被持久化到 MAC 签名的 cookie 并发送到客户端.

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.

您遇到的问题是 session 是在每个请求上重建的(因为它被发送到客户端,然后客户端将它发回给我们),而 上的数据集g 仅在这个请求的生命周期内可用.

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.

最简单要做的事情(注意simple !=secure - 如果您需要安全,请查看 Flask-Login) 是简单地将用户的 ID 添加到会话并在每个请求上加载用户:

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 global的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆