I am trying to write a flask extension that should retain some information between requests. This works fine when I start Werkzeug using a single process, but when I start several processes, I get some strange behavior that I don't understand. Take this simple application as an example:
from flask import Flask app = Flask(__name__) class Counter(object): def __init__(self, app): print('initializing a Counter object') self.app = app self.value = 0 def increment(self): self.value += 1 print('Just incremented, current value is ', self.value) counter = Counter(app) @app.route('/') def index(): for i in range(4): counter.increment() return 'index' if __name__ == '__main__':
For the first two scenarios, it works exactly as I expected: the Counter object is initialized once, and then it grows with each request for the '/' route. When I run it with the third script (process transfer = 2), I get this as output:
initializing a Counter object * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Just incremented, current value is 1 Just incremented, current value is 2 Just incremented, current value is 3 Just incremented, current value is 4 127.0.0.1 - - [30/Aug/2015 09:47:25] "GET / HTTP/1.1" 200 - Just incremented, current value is 1 Just incremented, current value is 2 Just incremented, current value is 3 Just incremented, current value is 4 127.0.0.1 - - [30/Aug/2015 09:47:26] "GET / HTTP/1.1" 200 - Just incremented, current value is 1 Just incremented, current value is 2 Just incremented, current value is 3 Just incremented, current value is 4 127.0.0.1 - - [30/Aug/2015 09:47:27] "GET / HTTP/1.1" 200 -
Counter.value seems to return a state to it immediately after initialization without actually re-initializing. Can anyone shed light on what Werkzeug is doing internally for this to happen? I would also love to know if there is a way to do as I would naively expect (two processes, each with its own Counter instance). Thanks!
source share