python - Are global variables thread safe in flask? -


in app state of common object changed making requests, , response depends on state.

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') 

if run on development server, expect 1, 2, 3 , on. if requests made 100 different clients simultaneously, can go wrong? expected result 100 different clients each see unique number 1 100. or happen:

  1. client 1 queries. self.param incremented 1.
  2. before return statement can executed, thread switches on client 2. self.param incremented again.
  3. the thread switches client 1, , client returned number 2, say.
  4. now thread moves client 2 , returns him/her number 3.

since there 2 clients, expected results 1 , 2, not 2 , 3. number skipped.

will happen scale application? alternatives global variable should at?

you can't use global variables hold sort of data. not not thread safe, it's not process safe, , wsgi servers in production spawn multiple processes. not counts wrong if using threads handle requests, vary depending on process handled request.

the development server single thread, single process default. won't see behavior describe since each request handled synchronously. enable threads or processes , see it. app.run(threaded=true) or app.run(processes=10).

use data source outside of flask hold global data. database, memcached, or redis appropriate separate storage areas, depending on needs. use session simple data per-user.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -