【问题标题】:Not able to use global variables in a @app.route block in flask app无法在烧瓶应用程序的 @app.route 块中使用全局变量
【发布时间】:2021-06-10 07:44:41
【问题描述】:
from flask import Flask, request, render_template


app = Flask(__name__)

def fun(userAns="True", question="this is first question"):
    if question == "this is first question":
    
        if userAns == "True":
            return "actual first question", "Yes", "No", None
   
    elif question == "actual first question":
        if userAns == "True":
            return "2nd question to be asked after ans = true", "Yes", "No", None
        elif userAns=="False":
            return "2nd question to be asked after ans = false",  "Yes", "No", None

question = None
userAns = None

@app.route("/", methods=["POST", "GET"])
def hello():
    a=0
    while a < 1:
        question = "this is first question"
        userAns = 'True'
        returnValue = fun(userAns, question)
        a += 1
        
    if request.method == "POST":
        userAns = request.form["answer"]
        print(userAns)
        returnValue = fun(userAns, question)
        question=returnValue[0]
    return render_template("index.html",question=returnValue[0], option1= returnValue[1],option2=returnValue[2],option3=returnValue[3])

if __name__ == "__main__":
    app.run(debug=True)

这里我想在@app.route 中调用fun() 函数,但为此我必须初始化一些变量,因为它们将在下一次迭代中更新。我在调试器中观察到每个变量在@app.route 的末尾都有它的初始值,所以我尝试将这些变量设为全局变量,但由于某种原因它没有采用全局变量。

【问题讨论】:

    标签: python flask backend web-development-server


    【解决方案1】:

    要更新函数中的全局变量,请在 hello 函数的开头使用 global variable_name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多