While writing a flask server I find myself in a situation similar to this:
from flask import Flask, jsonify
app = Flask(__name__)
x = 0
@app.route('/method_a', methods=['GET'])
def method_a():
global x
x = x + 1
return jsonify({'mesaage': 'value of x incremented by 1 is: '+str(x)}), 200
@app.route('/method_b', methods=['GET'])
def method_b():
global x
x = x + 2
return jsonify({'message': 'value of x increased by 2 is: '+str(x)}), 200
Here, I have two methods which I am trying to invoke through GET requests from clients. So, when a single client makes 2 requests to '/method_b', the output should be 4, and so on. Now my problem is that, when the server will run in the real web, multiple clients will try to invoke its methods. So if first client invokes '/method_a' once, he gets output 1, meanwhile other clients will also invoke the methods, thus, changing the value of x. Thus when first client will make its 2nd request on '/method_a', it will not get the output as 2.
But I want to make a server which treats the variable values as different for different clients and show them only their version of the variable values. I am using global variables because both the methods need this variable to function, and since they are invoked by a GET request, I can't pass the value of variable through client. How to approach this problem? Is there a better way to write this code to addres the above problem?