Preserving global state in a flask application [duplicate]

Based on your question, I think you’re confused about the definition of “global”.

In a stock Flask setup, you have a Flask server with multiple threads and potentially multiple processes handling requests. Suppose you had a stock global variable like “itemlist = []”, and you wanted to keep adding to it in every request – say, every time someone made a POST request to an endpoint. This is totally possible in theory and practice. It’s also a really bad idea.

The problem is that you can’t easily control which threads and processes “win” – the list could up in a really wonky order, or get corrupted entirely. So now you need to talk about locks, mutexs, and other primitives. This is hard and annoying.

You should keep the webserver itself as stateless as possible. Each request should be totally independent and not share any state in the server. Instead, use a database or caching layer which will handle the state for you. This seems more complicated but is actually simpler in practice. Check out SQLite for example ; it’s pretty simple.

To address the ‘flask.g’ object, that is a global object on a per request basis.

http://flask.pocoo.org/docs/api/#flask.g

It’s “wiped clean” between requests and cannot be used to share state between them.

Leave a Comment