我對此很陌生。我不明白爲什麼應用似乎無法保留隨機生成的數據。 get_question()返回一個帶有2個鍵值對的字典。問題/答案是從這個函數中隨機生成的。每次調用flash()時,它都會重新運行index()中的所有代碼?當閃現的消息出現時,用戶的答案與輸入的內容相關,但問題和正確答案似乎隨機出現 - 表明每次點擊提交時都會調用整個index()。我如何防止這種情況發生?我應該使用'會話'嗎?Python - 燒瓶 - 理解routing/flash的行爲()
更新:更具體一點 - 我不明白爲什麼閃爍的消息與瀏覽器中呈現的內容完全無關。看起來好像flash()正在對我的get_question()函數運行自己的調用,並因此得到不同的問題/答案,以顯示那些?
Here are some images that show the problem
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
user = {'nickname': 'test'} # fake user
question = question_gen.get_question()
answer = AnswerQuestionForm()
q = question['question']
correct = question['answer']
response = ""
if answer.validate_on_submit():
you_said = request.form['answer']
print("You said {}, to the question {}. correct was {}".format(you_said, q, correct))
flash("The question was: %s" % q)
flash("The correct answer was: %s" % correct)
flash("You said: %s" % you_said)
return redirect(url_for('index'))
return render_template('index.html',
title='Home',
user=user,
question=question,
answer=answer,
response=response)
謝謝這是有幫助的 - 我添加了一些圖像來顯示我的具體問題。我怎樣才能讓flash()識別出瀏覽器中出現的問題,而不是它看起來如何並得到自己的問題? –
再次感謝您的幫助 - 我無法識別問題/答案,因爲它們基於隨機數生成,而不是從列表中隨機選擇。任何想法我應該怎麼做呢? –
您可能有一個問題的原始列表,所以有一個訂單。如果我把這份名單給了你,然後我扔了一對骰子,我可以說「我隨機選擇了問題...... 4」。然後你可以低頭看第四個問題,找到我想說的那個。 – Doobeh