Python中的全局变量在多个路由/页面中使用

Python中的全局变量在多个路由/页面中使用,python,flask,routes,global-variables,Python,Flask,Routes,Global Variables,您好,我想知道是否可以在我使用的路由之间使用全局变量 基本上,我有一个页面/路径加载多项选择题,并将正确答案存储在变量答案中,我希望另一个路径使用该答案变量 我尝试创建一个全局变量,然后将其分配给第一条路径内的答案值,但无法使其工作 这是相关代码- global glob_answer glob_answer = "Answer" # initialized to this value for testing (I get nothing) @app.route('/quiz') def

您好,我想知道是否可以在我使用的路由之间使用全局变量

基本上,我有一个页面/路径加载多项选择题,并将正确答案存储在变量答案中,我希望另一个路径使用该答案变量

我尝试创建一个全局变量,然后将其分配给第一条路径内的答案值,但无法使其工作

这是相关代码-

global glob_answer
glob_answer = "Answer"    # initialized to this value for testing (I get nothing)

@app.route('/quiz')
def quiz():
    cursor = g.conn.execute("select actor_name, categ, a_name, year, title from win_actor order by random() limit 1")

    c_names  = []
    category = ""
    alias    = ""
    year     = ""
    title    = ""
    for name in cursor:
        c_names.append(name[0]) # can also be accessed using result[0]

#SETTING GLOBAL VARIABLE EQUAL TO ANSWER
        answer  = name[0]
        glob_answer = answer
        category = name[1]
        year     = str(name[3])
        title    = name[4]
        cursor2 = g.conn.execute("select alias from awards where a_name = " + "'" + name[2] + "'" + " limit 1")
        for columns in cursor2:
            alias = columns[0]
        cursor2.close()
    cursor.close()
    cursor = g.conn.execute("select * from actor limit 4")
    for name in cursor:
        if name[0] not in c_names:
            c_names.append(name[0]) # can also be accessed using result[0]
    cursor.close()
    shuffle(c_names)
    context = dict(data = c_names, categ = category, award_name = alias, year = year, title = title, answer = answer)
    return render_template("quiz.html", **context)

#Second Route
@app.route('/answer')
def answer():
#TRYING TO PASS VALUE TO NEW LOCAL VARIABLE
    global glob_answer 
    answer = glob_answer   
    return render_template("answer.html")

当我在html中显示“answer”变量时,不会显示任何内容

最好的方法是将问题的唯一ID发送到答案路径,然后从DB中选择答案并在模板中呈现:

@app.route('/answer/<question_id>')
def answer(question_id):
    # Here you need to select answer from database
    answer = get_answer(question_id)   
    return render_template("answer.html")

你的意思是把问题和答案一起作为数据库的一部分吗?目前,我的问题实际上并没有存在于数据库中——它们只是使用数据库中的字段硬编码到html中。没错。例如,您可以将您的问题存储在数据库中,然后您的测验路线将选择问题并呈现它,然后您可以通过向带有问题id的答案路线发送ajax请求来检查正确答案