Using flash and get_flashed_messages
- From:
- Emiel van de Laar
- Date:
- 2011-08-10 @ 13:10
Hey guys,
I had some view code as follows:
@bp.route('/', methods=['GET', 'POST'])
def search():
if len(result) > 1000:
flash("Max result reached")
if emit_result_as_csv:
return make_response(...)
return render_response('template/result.html', result=result)
Where the result.html template would call 'get_flashed_messages'.
When an end-user would choose to emit the result as CSV and then come
back and perform the same search with an HTML response the resulting
response displayed _TWO_ 'flashed' messages. One from the CSV request
and one from the HTML request.
This is because flashed messages get stored in the session until the
'get_flashed_messages' gets called. I ended up having to call this
function to clear the messages before returning the CSV response.
I understand what happens now. I guess I was under the impression that
flash message clearing was somehow enforced in a deeper layer. However,
messages stick around until you call 'get_flashed_messages'.
Anyway... The 'quick start' guide states:
"""
The flashing system basically makes it possible to record a message at
the end of a request and access it next request and only next request.
"""
And is repeated at:
http://flask.pocoo.org/docs/patterns/flashing/#message-flashing-pattern
Perhaps we can reword this?
In addition calling `flash` in a view function and then calling
`get_flashed_messages` in the template happens in the same request.
So it is equivalent to passing some 'mesg' parameter to the template.
return render_response('template/result.html', mesg=error, result=result)
Perhaps I should be using that idiom instead. Can someone chime in on
the advantages/disadvantages.
Just sharing me experience.
Thanks,
- E