在我的Flask网站上,我有一个名为' thisQuestion'的会话变量。每次加载页面时,简单地增加1。基本上,页面返回数据库中的问题,用户可以说明问题是对还是错。会话变量增加1,以了解它所处的问题以及从数据库接收的问题。
session['thisQuestion'] += 1
但是,如果我在第3个问题页面上并返回到第2个问题页面,则会话变量仍保留在' 3'当我希望它在' 2'。如果我在第3页并回到' 1'我希望这也会发生。在第1页。
有人会怎么做?
答案 0 :(得分:0)
为了跟踪用户前进或后退或跳过其他问题,您需要更好的状态管理。
我的建议是在网址查询字符串中包含预期的问题编号(或使其更友好的SEO,只需在网址中包含问题编号)
例如:
要收到问题1,请转到:
http://example.com/questions?num=1 # querystring method
http://example.com/questions/1 # using url method (preferred)
在烧瓶中,您的questions
视图将检索相应的问题编号(如果使用网址方法)
@app.route('/questions/<int:num>')
def questions(num):
# This part disallows the user from jumping a future question
# without first answering all the questions that lead up to it
# i.e a user cannot go from question 1 to question 8 without
# first answering questions 2 - 7 but once they've answered
# question 8 they can jump back to question 2 and then jump to
# question 9
highest_num_seen = session.get('highest_num_seen', 1)
if num > highest_num_seen:
num = highest_num_seen
question = db.load_question(num) # Load your question from db
# update highest_num_seen if and only if it is the next question
# from what the user last answered
if num == highest_num_seen + 1:
session['highest_num_seen'] = num
render_template('blahblah')