I am trying to find out how to work with global variables in Flask:
gl = {'name': 'Default'}
@app.route('/store/<name>')
def store_var(name=None):
gl['name'] = name
return "Storing " + gl['name']
@app.route("/retrieve")
def retrieve_var():
n = gl['name']
return "Retrieved: " + n
Storing the name and retrieving it from another client works fine. However, this doesn't feel right: a simple global dictionary where any session pretty much simultaneously can throw in complex objects, does that really work without any dire consequences?
Similarly, the FLASK_ENV variable sets the environment on which we want our flask application to run. For example, if we put FLASK_ENV=development the environment will be switched to development. By default, the environment is set to development. Now let us look at some example so that one can easily understand “what happens in reality”!
Please note: While this makes sense for python requests, it might not make sense for Flask apps which can run in threads and workers. Defining a global like this might cause unexpected results when used in projection and you would be better off using a persistent data storage system like memcache or some other database.
Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
To create a global variable inside a function, you can use the global keyword. If you use the global keyword, the variable belongs to the global scope: Also, use the global keyword if you want to change a global variable inside a function.
No, it doesn't work, not outside the simple Flask development server.
WSGI servers scale in two ways; by using threads or by forking the process. A global dictionary is not a thread-safe storage, and when using multi-processing changes to globals are not going to be shared. If you run this on a PAAS provider like Google App Server, the processes aren't even forked; they are run on entirely separate machines even.
Use some kind of backend storage instead; a memcached server, a database server, something to control concurrent access and share the data across processes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With