Inconsistent globals in Flask

后端 未结 1 1645
无人共我
无人共我 2021-01-15 10:21

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

相关标签:
1条回答
  • 2021-01-15 10:50

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题