Are Global Variables Thread-Safe in Flask?
In Flask applications, maintaining data consistency is crucial when handling concurrent requests. Using global variables to store shared data can introduce thread safety issues.
Unsafe Use of Global Variables
Consider the following example:
class SomeObj(): def __init__(self, param): self.param = param def query(self): self.param += 1 return self.param global_obj = SomeObj(0) @app.route('/') def home(): flash(global_obj.query()) render_template('index.html')
When multiple clients request this route simultaneously, the expected result is a unique number for each client (e.g., 1, 2, 3...). However, due to thread interleaving, the following race condition may occur:
Alternatives to Global Variables
To avoid thread safety issues, consider the following alternatives:
Other Considerations
The above is the detailed content of Are Flask's Global Variables Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!