analitics

Pages

Sunday, August 4, 2019

Python 3.7.3 : Using the flask - part 008.

The tutorial for today will show you how to understand the flash method and fix exceptions.
First, the Flask module contains a flash method which passes a message to the next request, which generally is a template.
This lets you create feedback to users of a web application is critical, from notifications and error messages to warnings and progress alerts.
This system allows us to record a message at any point within a request, then display it at the start of the next request (and only the next request), see the documentation.
You need to import the flash with:
from flask import flash
The flash function takes up to 2 arguments, a message and a category like this: flash("message", "category").
In the next example, the random range output named out will send a flash message by category.
The flash warning category will send the number get by the random and will be into a range of 1 and 3.
Flashed messages are stored in the session until they are read it.
The HTML5 page named home.html can be found at my GitHub project.
This source code will send one message by flash and show two messages into a webpage.
@app.route('/',methods = ['GET','POST'])
def home():
    # test flash message
    out = random.randint(1,10)
    if out in range(1,3):
        flash(str(out),"warning" )
    if out in range(4,6):
        flash("This is a flash test for home.html with result:","success")
    if out in range(7,10):
        flash("This is a flash test for home.html with result:","danger")  
    return render_template("home.html")
The next example shows you how to use flash and exceptions to create an output error with render_template_string.
The output exception sends by flash without an HTML5 page request.
from flask import render_template_string
...
# fix Exception error , like 404
@app.errorhandler(Exception)
def page_not_found(e):
    flash(e, type(e))  
    return render_template_string('''
      {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
          {% set printed_messages = dict() %}
          {% for category, message in messages %}
            {% if message not in printed_messages %}
              
{{message}}
{% set x = printed_messages.__setitem__(message, "value") %} {% endif %} {% endfor %} {% endif %} {% endwith %} ''')
If you put a bad path URL intro the server ( http://127.0.0.1:5000/bad ) then you get the result of the exception 404:
404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Using the flash you can create your own notification system.