Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with a global singleton in Flask (WSGI), do I have to worry about race conditions?

Tags:

The hello world demo for Flask is:

from flask import Flask app = Flask(__name__)  @app.route("/") def hello():     return "Hello World!"  if __name__ == "__main__":     app.run() 

What if I modified this like so:

from flask import Flask app = Flask(__name__)  a = 1 b = 2 c = 3  @app.route("/") def hello():     a += 1     b += a     c += b     return "Hello World!"  if __name__ == "__main__":     app.run() 

I understand WSGI application might have multiple threads. The hello function could be running on multiple threads at the same time, and then we'd have a race condition. Is this correct? If the above code is not thread safe, what can I do to make it thread safe?

Avoiding globals is a possible solution, but can you always avoid globals? What if I want something like a python object cache?

like image 602
Buttons840 Avatar asked Apr 16 '12 21:04

Buttons840


People also ask

Are global variables thread safe in Flask?

Flask code has to be thread-safe, also called re-entrant. Local variables and parameters are always thread-safe. Instance variables, class variables, and global variables may not be thread-safe (but they might be). Nevertheless, threads and shared variables can be useful.

Why are global variables not thread safe?

Global variables are still not thread safe because there's still no protection against most race conditions. You can still have a scenario where one worker gets a value, yields, another modifies it, yields, then the first worker also modifies it.

Is Flask app a singleton?

In Python, using singleton pattern is not needed in most cases, because Python module is essentially singleton. But you can use it anyway. To use Flask (or any other web framework) app as singleton, simply try like this. Or inherite Flask class and make itself as a singleton.


1 Answers

You could try the Local class from werkzeug. Here's some info about it: Context Locals

Example:

from flask import Flask from werkzeug.local import Local app = Flask(__name__) loc = Local() loc.a = 1 loc.b = 2 loc.c = 3  @app.route("/") def hello():     loc.a += 1     loc.b += loc.a     loc.c += loc.b     return "Hello World!"  if __name__ == "__main__":     app.run() 
like image 93
Florentin Avatar answered Nov 08 '22 21:11

Florentin