Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65941738/python-variable-is-declared-and-still-gives-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...