我有一条路线可以向用户显示随机问题,该路线是使用random.choice(list_of_questions)选择的。 然后,用户提交问题的答案,所有答案均保存到我的数据库中。但是,当查询数据库时,相关的问题始终是随机的,与向用户显示的问题不同。
到目前为止,我已经尝试将get和post方法组合在一起,以便它们具有相同的变量..没有用。我也尝试过在全局范围内声明随机变量,但这恰好使用户只能看到一个问题。
初始化 .py
from flask import Flask
from random import choice
app = Flask(__name__)
question_list = ['question_1', 'question_2', 'question_3', 'etc']
@app.route('/', methods = ['GET','POST')
def question():
question = choice(question_list)
if request.method == 'POST':
answer = request.form.get('answer')
new_qa = QA(answer = answer, question = question)
db.session.add(new_qa)
db.session.commit()
else:
return render_template('question.html', question=question)
question.html
<h1>{{ question }}<h1>
<form method='POST' action = "/">
<input type = 'text' name = 'answer'>
</form>
提交表单时,数据库应将显示的问题与用户答案一起保存。而是保存一个随机问题。