【问题标题】:Revert back to previous flask session variables when going back a page返回页面时恢复到以前的烧瓶会话变量
【发布时间】:2015-06-18 08:20:02
【问题描述】:

在我的 Flask 网站上,我有一个名为“thisQuestion”的会话变量,每次加载页面时它都会简单地递增 1。基本上,页面从数据库返回问题,用户可以说明他们的问题是对还是错。 session 变量加 1 以知道它在处理哪个问题以及从数据库接收什么问题。

session['thisQuestion'] += 1

但是,如果我在第 3 个问题页面并返回到第 2 个问题页面,会话变量在我希望它位于“2”时仍保持在“3”。如果我在第 3 页并返回到第 1 页的“1”,我也希望发生这种情况。

有人会怎么做?

【问题讨论】:

  • 请展示一些代码示例,说明您如何实现增量 1
  • @junnytony 我添加了一些代码,但是我不知道还有什么必要的,所以我改进了这个问题,以便更容易理解。

标签: python session flask


【解决方案1】:

为了跟踪用户前进和后退或跳到不同的问题,您将需要更好的状态管理。

我的建议是在 url 查询字符串中包含预期的问题编号(或者为了使其对 SEO 更友好,只需在 url 中包含问题编号)

例如:

要接收第 1 题,请访问:

http://example.com/questions?num=1    # querystring method
http://example.com/questions/1   # using url method (preferred)

在烧瓶中,您的questions 视图将检索适当的问题编号(如果使用 url 方法)

@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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 2016-06-14
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多