Flask Message Flashing

flash(): to pass a message to the next request, which generally is a template

flash(message, category)

message: The actual message you want to be flashed.
category: 'message'、'info'、'warning' or '
error', optional.

get_flashed_messages(): to remove(take out) message from session

get_flashed_messages(with_categories, category_filter):

with_categories: a tuple if received messages are having category,
optional
category_filter: to display only specific messages,
optional

a template block of a flashes received message:
{% with messages = get_flashed_messages() %}
   {% if messages %}
      {% for message in messages %}
         {{ message }}
      {% endfor %}
   {% endif %}
{% endwith %}

example:

vi templates/flash.html

<!doctype html>
<html>

  <head>
    <title>Flask Message flashing</title>
  </head>

  <body>

    <h2>Flask Message Flashing below</h2>

    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <ul>
          {% for message in messages %}
          <li>{{ message }}</li>
          {% endfor %}
        </ul>
      {% endif %}
    {% endwith %}

    <h2>Flask Message Flashing above</h2>


    <p>Do you want to <a href = "{{ url_for('login') }}">
      <b>log in?</b></a></p>

  </body>
</html>
vi templates/flash_login.html
<!doctype html>
<html>
  <body>

    <h1>Login</h1>

    {% if error %}
    <p><strong>Error:</strong> {{ error }}
    {% endif %}

    <form action = "/flash_login" method = "post">
      <dl>
        <dt>Username:</dt>
        <dd>
          <input type = "text" name = "username"
            value = "{{request.form.username }}">
        </dd>

        <dt>Password:</dt>
        <dd><input type = "password" name = "password"></dd>
      </dl>
     
      <p><input type = "submit" value = "Login"></p>
     
    </form>

  </body>
</html>

vi flash.py
from flask import Flask, redirect, render_template, request, url_for, flash
ap = Flask(__name__)
ap.secret_key = '<random string>'

@ap.route('/flash')
def flashing():
   return render_template('flash.html')

@ap.route('/flash_login', methods = ['GET', 'POST'])
def login():
   error = None

   if request.method == 'POST':
      if (request.form['username'] != 'admin' or
          request.form['password'] != 'admin'
         ):
         error = 'Invalid username or password. Please try again!'
      else:
         flash('Hi, Admin!')
         return redirect(url_for('flashing'))

   return render_template('flash_login.html', error = error)

if __name__ == "__main__":
   ap.run(host='0.0.0.0')

python flash.py

#open http://<ip/url>:5000/flash




Leave comments

authimage

Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved