Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Message Flashing API

Flask Message Flashing API

The message flashing (Flash) mechanism is used to display one-time feedback messages in the next request, typically for 'operation successful' or 'input error' notifications.

Flask stores messages in the Session and automatically clears them after they are read.


The flash Function

Parameters Type Default value Description
message str Required The text of the message to display
category str "message" Message category, recommended values: message, success, error, warning, info

The get_flashed_messages Function

Parameters Type Default value Description
with_categories bool False When True, returns a list of (category, message) tuples
category_filter iterable () Return only messages of the specified categories
Return Value Description
with_categories=False Returns a list of message texts: ["msg1", "msg2"]
with_categories=True Returns a list of category+message tuples: [("success", "msg1"), ("error", "msg2")]

Using in Templates

get_flashed_messages() can be called directly in templates without being passed through render_template.

Example

{% with messages = get_flashed_messages(with_categories=true) %}

    {% if messages %}

        {% for category, message in messages %}

       

{{ message }}

        {% endfor %}

    {% endif %}

{% endwith %}

{% for msg in get_flashed_messages(category_filter=["error"]) %}

   

{{ msg }}

{% endfor %}


Code Example

Example

from

flask

import

Flask

,

flash

,

get_flashed_messages

,

redirect

,

url_for

,

request

app

=

Flask

(

name

)

app.

secret_key

=

"secret"

@

app.

route

(

"/post"

,

methods

=

[

"GET"

,

"POST"

]

)

def

create_post

(

)

:

   

if

request.

method

==

"POST"

:

        title

=

request.

form

.

get

(

"title"

,

""

)

.

strip

(

)

       

if

not

title:

            flash

(

"Title cannot be empty"

,

"error"

)

       

else

:

            flash

(

f

"Article '{title}' published successfully!"

,

"success"

)

           

return

redirect

(

url_for

(

"create_post"

)

)

       

return

redirect

(

url_for

(

"create_post"

)

)

   

GET request: Retrieve and display all messages

    messages

=

get_flashed_messages

(

with_categories

=

True

)

   

return

render_template

(

"post.html"

,

messages

=

messages

)

Flash messages are stored in the Session, so you must set SECRET_KEYthe secret key. Messages are only visible in the next request that reads them, and are automatically cleared afterward.