Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask global variables [duplicate]

Tags:

python

flask

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?

like image 763
Passiday Avatar asked May 04 '14 14:05

Passiday


People also ask

What does the flask_env variable do?

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”!

Is it possible to define a global for a flask application?

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.

What is a global variable?

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.

How to create a global variable inside a function in JavaScript?

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.


1 Answers

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.

like image 95
Martijn Pieters Avatar answered Oct 19 '22 18:10

Martijn Pieters