Thinked
Thinked

Reputation: 49

Python variable is declared and still gives error

I want to assign the data from the request to the variable currentKampjson that is used multiple places in the code. But when I try to assign currentKampjson to anything it gets declared as a new variable, this applies to every variable.

currentKampjson is a dictionary type variable

currentKampjson = {"info":1, "info2":3}

@app.route("/stream/currentkamp")
def streamCurrentKamp():
    return render_template("stream/currentKamp.html", kamp = currentKampjson)

@app.route("/currentKamp/getKamp")
def getCurrentKamp():
    return jsonify(currentKamp)
    
print(currentKampjson)
@app.route("/currentKamp/update", methods=["POST"])
def updateCurrentKamp():
    indata = eval(request.data)
    
    currentKampjson = indata
    with open("jsonFiles/kamper/currentKamp.json","w") as f:
        json.dump(indata, f)
    return "SUCCESS"

This code runs fine, even though I am using currentKampjson here:

@app.route("/currentKamp/update", methods=["POST"])
def updateCurrentKamp():
    indata = eval(request.data)
    print(currentKampjson)
    #currentKampjson = indata
    with open("jsonFiles/kamper/currentKamp.json","w") as f:
        json.dump(indata, f)
    return "SUCCESS"

Wierd variable interaction

Upvotes: 0

Views: 45

Answers (1)

dukkee
dukkee

Reputation: 1122

In the current case, you need to use global keyword to your variable, but in a common case, global variables aren't a good practice.

More about scopes you can read e.g. here:

https://realpython.com/python-scope-legb-rule/ https://matthew-brett.github.io/teaching/global_scope.html

currentKampjson = {"info":1, "info2":3}

@app.route("/stream/currentkamp")
def streamCurrentKamp():
    global currentKampjson
    return render_template("stream/currentKamp.html", kamp=currentKampjson)

@app.route("/currentKamp/getKamp")
def getCurrentKamp():
    return jsonify(currentKamp)
    
print(currentKampjson)

@app.route("/currentKamp/update", methods=["POST"])
def updateCurrentKamp():
    global currentKampjson
    indata = eval(request.data)
    
    currentKampjson = indata

    with open("jsonFiles/kamper/currentKamp.json", "w") as f:
        json.dump(indata, f)

    return "SUCCESS"

Upvotes: 1

Related Questions