Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top