1

The goal of my code is to place it into two EC2 instances which is then connected to a load balancer to distribute requests between the two instances.

This is my code which I am first trying to test in my local before I test it in the EC2 instances and then ultimately test everything with the load balancer as well.

from flask import Flask,request,session
##global s
s = 0
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def disp():
    if request.method == "GET":
        global s
        s = 0 
        return str(s)
    if request.method == "POST":
        global s
        s = request.json["num"]
        return str(s)

if __name__ =="__main__":
    app.run()
    ##app.run('0.0.0.0', port=80)

The error that returns when I run locally is SyntaxError: Name 's' is used prior to global declaration. I tried removing the s=0 after the import line but the error still persists.

  • Shouldn't you make s global from the beginning in line 2? – Jakob F Feb 18 '20 at 15:29
  • 1
    @JakobF global scope already means the variable is global. The commented line you refer to is not needed at all. `global s` means you want to overwrite contents of the global var. – h4z3 Feb 18 '20 at 15:32
  • I'm not sure what you are trying to achieve here, but it might be worth noting that `s` is only global *per process*. Usually, you run an application with multiple processes per server, so even with only one EC2 instance, you will receive different/unpredictable values for `s`. – Daniel Hepper Feb 18 '20 at 15:35

1 Answers1

5

You have two global s in your disp function and the second one says something's wrong because it sees s = 0 before.

Ideally, put global definitions just after declaring the function:

from flask import Flask,request,session

s = 0
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def disp():
    global s
    if request.method == "GET":
        s = 0 
        return str(s)
    elif request.method == "POST":
        s = request.json["num"]
        return str(s)

if __name__ =="__main__":
    app.run()
    ##app.run('0.0.0.0', port=80)

Also changed second if to elif.

h4z3
  • 5,265
  • 1
  • 15
  • 29