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



嗨,我想知道是否可以在路线之间使用全局变量(我使用的是烧瓶)

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

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

这是相关代码——

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发送到answer路由,然后从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")

相关内容

  • 没有找到相关文章