Flask中的全局变量不一致 [英] Inconsistent globals in Flask

查看:183
本文介绍了Flask中的全局变量不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单,用户可以根据其权限查看不同的菜单项.我检查用户登录时是否具有该选项,将其存储在全局变量中,并在呈现菜单时检查该变量.

I have a menu where users can see different menu items depending on their permissions. I check whether the users has the option or not when logging in, store it in a global variable, and check that variable when rendering the menu.

在生产中,菜单仅在大约50%的时间正确显示.有时会设置该值,有时会为空.为什么它不能正常工作?

In production, the menu only shows up correctly about 50% of the time. Sometimes the value is set, sometimes it is empty. Why isn't this working correctly?

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = User.get(request.form['username'])

        if user.user is None:
            return redirect('/login/')

        if user and check_password_hash(user.user.password, request.form['password']):
            login_user(user)
            if isinstance(current_user.user, UserTypeOne):
                group = UserGroup.query.filter_by(id=int(current_user.user.group)).first()
                app.jinja_env.globals['group_access_to_feature_one'] = group.group_access_to_feature_one

            return redirect(request.args.get('next') or url_for('index'))

        return redirect(url_for('login'))

header模板具有检查该值的条件:

The header template has a conditional to check that value:

{% if group_access_to_feature_one%}<ul>...</ul>{%endif%}

调试时,我放{{ group_access_to_feature_one }}来查看值,有时是True,有时是空的.

When debugging, I put {{ group_access_to_feature_one }} to see the value, and sometimes it is True and sometimes it's empty.

推荐答案

在生产环境中(有时可能在开发环境中),您正在运行多个进程.每个进程都会创建自己的应用程序副本,因此只有处理登录请求的进程中的应用程序才能看到对环境的更改.不鼓励使用Python全局变量来存储状态的主要原因之一. app.jinja_env.globals只能在设置过程中进行修改,以使每个进程/线程保持一致.

In production (and possibly sometimes on dev), you are running with multiple processes. Each process creates its own copy of the app, and so only the app in the process that handled the login request will see the changes to the env. This is one of the main reasons using Python globals to store state is discouraged. app.jinja_env.globals is meant to be modified only during setup so that each process/thread remains consistent.

使用数据库或其他存储(例如Redis)来存储和访问全局状态.使用session存储有关特定浏览器会话的信息,例如已登录的用户.使用app.before_request回调为每个请求加载每个用户的状态.

Use a database or other storage such as redis to store and access global state. Use the session to store information about a specific browser session, such as the logged in user. Load the state for each user on each request using an app.before_request callback.

您的代码也不正确,因为每次用户登录时都会更改全局Flask环境.因此,每个用户的值将基于 last 用户登录并设置值.

Your code is also incorrect because the global Flask environment is changed every time a user logs in. So the value of the value for every user will be based on the last user to log in and set the value.

这篇关于Flask中的全局变量不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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