how to clear existing flash messages in Flask
Asked Answered
O

2

10

I have a warning flash message in Flask that that appears before the user tries to submit a form based on background information about the user. If the user goes ahead and submits the form the way they were warned not to, they are prevented and see a second flash message. I'd like to clear the first flash message before the user sees the second.

I've read the Flask documentation on flash messages and tried to google for the answer. I also read some of the Flask source code. No solution jumps out at me.

Can anyone help me figure out how to clear a flash message?

Overstretch answered 13/8, 2020 at 1:55 Comment(1)
Flash messages are designed to provide user feedback (user action -> processing -> flash message). Your question sounds like you abused them to emphasize form instructions. That should be done in the form/template.Hermineherminia
M
10

This way you can clear the flash message as there is no predefined method to clear the flash message in Flask flash helpers. You can try the below code. It works for me and maybe useful to you.

session.pop('_flashes', None)
Manualmanubrium answered 13/8, 2020 at 2:56 Comment(4)
I should have said this in my question, but I tried this and it doesn't appear to work for me. The reason I didn't say it was that I wasn't sure, after I tried it and it didn't work, that I had understood the function of that line.Overstretch
Never mind, in the process of editing my question with my code I've either figured out why it wasn't working for me and/or made a change to my code that is now making it work. Thanks for your help!Overstretch
@Overstretch Can you explain what was the issue you were facing and how you solved it?Slash
@NitishVictor I wanted to make all existing flash messages disappear from the screen before displaying a new one (regardless of whether the user had cleared them). The line of code in the answer does that. I ultimately decided there were better ways to communicate to the user as KlausD suggested but it's still valuable to conclusively know how to do this.Overstretch
U
7

The flashes messages are stored in the session from flask, you can access them by typing.

session['_flashes']

This is a list with the messages stored on flash and it has a method clear() for, mm well yo know.

session['_flashes'].clear()

With that you can clean the stored messages on flash

Psdta: a little bit late but i just run in that issue and that is the way that i solved

Underwood answered 21/10, 2021 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.