Python - flask - understanding behaviour of routing / flash()
Question: I'm new to this. I can't understand why the app doesn't seem to be able to
keep hold of data that was randomly generated. get_question() returns a dict
with 2 key:value pairs. The question/answer are randomly generated from this
function. Every time flash() is called does it rerun all of the code inside
index()? When the flashed messages appear, the user's answer correlates to
what was typed in, but the question and correct answer seem to appear at
random - suggesting that the whole of index() is recalled every time submit is
clicked. How do I prevent that from happening? Should I be using 'session'?

UPDATE: To be more specific - I can't understand why the flashed messages are
completely unrelated to what is rendered in the browser. It seems as though
flash() is running its own call to my get_question() function and as a result
is getting different questions/answers to the ones shown?

[Here are some images that show the
problem](http://i.stack.imgur.com/fe2yT.png)

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


Answer: Think of `flash` like a filing cabinet. When you run the `flash('message')`
command all it does it store that message in the cabinet. If your templates
aren't actively looking in the cabinet for messages and taking them out,
they'll just keep building up. Sometimes that is confusing if you're not
immediately grabbing them on the next page, because when you do finally check
for them, the feedback that was generated at that point is now shown when it's
not longer useful (and likely is now confusing).

So if we assume a simple app like:

    
    
    from flask import Flask, flash, render_template
    from datetime import datetime
    
    app = Flask(__name__)
    app.secret_key = 'SO'
    
    @app.route('/')
    def store():
        flash('Stored at {}'.format(datetime.now()))
        return 'Reload to store another message!'
    
    
    @app.route('/contents/')
    def contents():
        return render_template('contents.html')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

With the contents of `contents.html` being:

    
    
    <!doctype html>
    <title>Messages</title>
    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul class=flashes>
        {% for message in messages %}
          <li>{{ message }}</li>
        {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}
    

If I go to `/` ten times, then load up `/contents/` It'll render my
`contents.html` template and display any waiting messages, essentially the
template code is going "Open the filing cabinet and pull out and display each
stored message, then throw it away". Generally the template code above is
included on **every** page template, so the flashed feedback is immediate and
doesn't build up.

**Update**

If you look at your program flow, the first time a user accesses the page
without a form submission, the following happens:

  1. Get random question
  2. Render the `index.html` template using the random question

When a user fills in the answer and submits the form, the following happens:

  1. Get a new random question
  2. Pull the `answer` field from the form
  3. Print the `answer` field from the form, the new randomly generated `question` and the new randomly generated `answer`.
  4. Flash the same information
  5. Redirect the user to the `index` view

At this point, nothing's been shown to the user, the (incorrect) flashed
messages are already in the cabinet, but we're not finished because of the
redirect:

  6. Get another random question
  7. Render the `index` template using the random question

What you're missing is the ability to look up an existing question, when the
form is submitted you need some logic to say "get me the question that matches
this submitted form entry so I can check the answer is correct".

Usually that's done with a `id` key `question = {id: 1, question: "1+1",
answer: "2"}` Then you could store that `id` as a hidden field in your form
and adjust your `get_question` to optionally take an `id` argument so it can
look through your list of questions to find the correct one.

