How to implement beautiful notifications in Flask


web development

Since you already know how to implement notifications, let’s see how to implement beautiful notifications in Flask.

Using boostrap, we can do:

# shopyoapi.html
def notify(message, alert_type="primary"):
    """
    Used with flash
        flash(notify('blabla'))

    Parameters
    ----------
    message: str
        message to be displayed

    alert_type: str
        bootstrap class

    Returns
    -------
    None
    """
    alert = """
    <div class="shopyo-alert alert alert-{alert_type} alert-dismissible fade show" role="alert"
        style="opacity: 0.98;">
      {message}

      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">×</span>
      </button>
    </div>
    """.format(
        message=message, alert_type=alert_type
    )

    scriptFade = """ 
    <script>
          setTimeout(function() {
            $('#flashed-messages').fadeOut('fast');
        }, 5000); // <-- time in milliseconds (5 secs)
    </script>
    """
    return alert + scriptFade


def notify_success(message):
    return notify(message, alert_type="success")


def notify_danger(message):
    return notify(message, alert_type="danger")


def notify_warning(message):
    return notify(message, alert_type="warning")


def notify_info(message):
    return notify(message, alert_type="info")


so that flash(notify\_success('Good')) will give you a green alert. But, be sure to include the bootstrap links in your page’s head. Part of the Shopyo internals series.

Written by

Abdur-Rahmaan Janhangeer

Chef

Python author of 7+ years having worked for Python companies around the world

Suggested Posts

How to implement notification in Flask

Implementing notifications in Flask goes way beyond using flash. You have to add this snippet in you...

Read article

How to Integrate Tinymce 5 with Flask (with csrf)

This article shows how to integrate Tinymce 5 with Flask even including csrf protection! Text area <...

Read article

How to Define Global Template Variables in Flask

When building Flask applications, it is very common to reuse the same variables across multiple temp...

Read article
Free Flask Course