Giter Site home page Giter Site logo

wiltonsr / flask-toastr Goto Github PK

View Code? Open in Web Editor NEW
51.0 2.0 8.0 37 KB

Showing non-blocking notifications with Flask's flash and toastr.

Home Page: https://pypi.org/project/Flask-Toastr/

License: MIT License

Python 95.84% HTML 4.16%
flask python27 python3 toastr jinja2 flask-extensions flask-extension hacktoberfest

flask-toastr's Introduction

Flask-Toastr

Showing Flask's flash non-blocking notifications in templates using toastr.

Donate to help keep this project maintained. Donate with PayPal button

Quick Start

Step 1: Initialize the extension:

from flask_toastr import Toastr
toastr = Toastr(app)

Step 2: In your <head> and bottom of <body>sections of your base template add the following code:

<html>
  <head>
    {{ toastr.include_jquery() }}
    {{ toastr.include_toastr_css() }}
    {{ toastr.message() }}
  </head>
  <body>
    {{ toastr.include_toastr_js() }}
  </body>
</html>

This extension also supports the Flask application factory pattern by allowing you to create a Toastr object and then separately initialize it for an app:

toastr = Toastr()

def create_app(config):
  app = Flask(__name__)
  app.config.from_object(config)
  # initialize toastr on the app within create_app()
  toastr.init_app(app)

app = create_app(prod_config)

Note that jQuery is required. If you are already including it on your own then you can remove the include_jquery() line. Secure HTTP is used if the request under which these are executed is secure.

The include_jquery(), include_toastr_js() and include_toastr_css() methods take some optional arguments. If you pass a version argument to any of these calls, then the requested version will be loaded from the default CDN. In addition, it is also possible to pass js_filename and css_filename to include_toastr_js() and include_toastr_css(), respectively.

Step 3: Use the flash() method with or without category in your views. For example:

@app.route('/')
def index():
    flash("All OK")
    flash("All OK", 'success')
    flash("All Normal", 'info')
    flash("Not So OK", 'error')
    flash("So So", 'warning')
    return render_template('index.html')

Or you could also use flash() method with custom titles, see #14 for details:

@app.route('/')
def index():
    flash("Message", 'Custom Title')
    flash({'title': "Custom Title", 'message': "Error Message"}, 'error')
    return render_template('index.html')

Step 4: Enjoy

Parameters

Config Default Possible Values Description Reference
TOASTR_VERSION '2.1.4' Releases from here Version of Toastr https://github.com/CodeSeven/toastr/tags
TOASTR_JQUERY_VERSION '2.1.0' Releases from here Version of JQuery https://releases.jquery.com/jquery/
TOASTR_CSS_FILENAME 'toastr.min.css' CDN file name CSS Filename used in CDN Toastr's link https://github.com/CodeSeven/toastr#cdns
TOASTR_JS_FILENAME 'toastr.min.js' CDN file name JS Filename used in CDN Toastr's link https://github.com/CodeSeven/toastr#cdns
TOASTR_CLOSE_BUTTON 'true' 'true' or 'false' Enable or Disable close button https://github.com/CodeSeven/toastr#close-button
TOASTR_SHOW_EASING 'swing' 'swing' or 'linear' Override the animation easing to show the toasts https://github.com/CodeSeven/toastr#animation-options
TOASTR_HIDE_EASING 'linear' 'swing' or 'linear' Override the animation easing to hide the toasts https://github.com/CodeSeven/toastr#animation-options
TOASTR_CLOSE_EASING 'linear' 'swing' or 'linear' Override the animation easing to close the toasts https://github.com/CodeSeven/toastr#animation-options
TOASTR_SHOW_METHOD 'fadeIn' 'fadeIn', 'fadeOut', 'slideDown', 'slideUp, 'show', 'hide' Override the animation method to show the toasts https://github.com/CodeSeven/toastr#animation-options
TOASTR_HIDE_METHOD 'fadeOut' 'fadeIn', 'fadeOut', 'slideDown', 'slideUp, 'show', 'hide' Override the animation method to hide the toasts https://github.com/CodeSeven/toastr#animation-options
TOASTR_CLOSE_METHOD 'fadeOut' 'fadeIn', 'fadeOut', 'slideDown', 'slideUp, 'show', 'hide' Override the animation method to close the toasts https://github.com/CodeSeven/toastr#animation-options
TOASTR_TIMEOUT 15000 any int value (in ms) Time to notification close https://github.com/CodeSeven/toastr#timeouts
TOASTR_EXTENDED_TIMEOUT 1000 any int value (in ms) Time to notification close after hover mouse or click https://github.com/CodeSeven/toastr#timeouts
TOASTR_POSITION_CLASS 'toast-top-right' 'toast-top-right', 'toast-bottom-right', 'toast-bottom-left', 'toast-top-left', 'toast-top-full-width', 'toast-bottom-full-width', 'toast-top-center', 'toast-bottom-center' Notification Positon https://codeseven.github.io/toastr/demo.html
TOASTR_PREVENT_DUPLICATES 'false' 'true' or 'false' Doesn't show same notification https://github.com/CodeSeven/toastr#prevent-duplicates
TOASTR_NEWS_ON_TOP 'false' 'true' or 'false' Notification's aparition order https://github.com/CodeSeven/toastr#display-sequence
TOASTR_PROGRESS_BAR 'true' 'true' or 'false' Enable or Disable progress bar https://github.com/CodeSeven/toastr#progress-bar
TOASTR_OPACITY True True or False Enable or Disable notification's opacity https://stackoverflow.com/a/17640150/7041939
Note: The values `true` and `false` are passed to JS, that is Case Sensitive.
Therefore they must be passed in lowercase.

Examples

To run the example in your local environment:

  1. Clone the repository:

        git clone https://github.com/wiltonsr/Flask-Toastr.git
        cd Flask-Toastr

  2. Create and activate a virtual environment:

        virtualenv env
        source env/bin/activate

  3. Install requirements:

        pip install -r 'example/requirements.txt'

  4. Run the application:

        python example/app.py

Function Reference

Consult the toastr documentation for more details.

Development

This extension is just a project to improve my python and flask skills. Any suggestions or tips are welcome.

flask-toastr's People

Contributors

jaugusto42 avatar ogabrielluiz avatar thetomcat avatar wiltonsr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

flask-toastr's Issues

'TOASTR_OPACITY = False' causing a KeyError

I attempted to use the TOASTR_OPACITY parameter in a project but get the following traceback KeyError:

Traceback (most recent call last):

File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 2464, in call
return self.wsgi_app(environ, start_response)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask_compat.py", line 39, in reraise
raise value
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask_compat.py", line 39, in reraise
raise value
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functionsrule.endpoint
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\app\main\views.py", line 20, in index
return render_template('index.html')
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\templating.py", line 137, in render_template
return _render(
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask\templating.py", line 120, in _render
rv = template.render(context)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\jinja2\environment.py", line 1090, in render
self.environment.handle_exception()
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\jinja2\environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\jinja2_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\app\templates\index.html", line 1, in top-level template code
{% extends 'base.html' %}
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\app\templates\base.html", line 31, in top-level template code
{{ toastr.include_toastr_css() }}
File "C:\Users\Samuel\PycharmProjects\flask-sake-project\venv\Lib\site-packages\flask_toastr.py", line 31, in include_toastr_css
return Markup('''
KeyError: '\n opacity'

Mismatched anonymous define()

When I try to use the flask_toastr module, I get this error that says

Mismatched anonymous define() module: function(e){return function(){function t(e,t,n){return g({type:O.error,iconClass:m().iconClasses.error,message:e,optionsOverride:n,title:t})}function n(t,n){return t||(t=m()),v=e("#"+t.containerId),v.length?v:(n&&(v=d(t)),v)}function o(e,t,n){return g({type:O.info,iconClass:m().iconClasses.info,message:e,optionsOverride:n,title:t})}function s(e){C=e}function i(e,t,n){return g({type:O.success,iconClass:m().iconClasses.success,message:e,optionsOverride:n,title:t})}function a(e,t,n){return g({type:O.warning,iconClass:m().iconClasses.warning,message:e,optionsOverride:n,title:t})}function r(e,t){var o=m();v||n(o),u(e,o,t)||l(o)}function c(t){var o=m();return v||n(o),t&&0===e(":focus",t).length?void h(t):void(v.children().length&&v.remove())}function l(t){for(var n=v.children(),o=n.length-1;o>=0;o--)u(e(n[o]),t)}function u(t,n,o){var s=!(!o||!o.force)&&o.force;return!(!t||!s&&0!==e(":focus",t).length)&&(tn.hideMethod,!0)}function d(t){return v=e("

").attr("id",t.containerId).addClass(t.positionClass),v.appendTo(e(t.target)),v}function p(){return{tapToDismiss:!0,toastClass:"toast",containerId:"toast-container",debug:!1,showMethod:"fadeIn",showDuration:300,showEasing:"swing",onShown:void 0,hideMethod:"fadeOut",hideDuration:1e3,hideEasing:"swing",onHidden:void 0,closeMethod:!1,closeDuration:!1,closeEasing:!1,closeOnHover:!0,extendedTimeOut:1e3,iconClasses:{error:"toast-error",info:"toast-info",success:"toast-success",warning:"toast-warning"},iconClass:"toast-info",positionClass:"toast-top-right",timeOut:5e3,titleClass:"toast-title",messageClass:"toast-message",escapeHtml:!1,target:"body",closeHtml:'ร—',closeClass:"toast-close-button",newestOnTop:!0,preventDuplicates:!1,progressBar:!1,progressClass:"toast-progress",rtl:!1}}function f(e){C&&C(e)}function g(t){function o(e){return null==e&&(e=""),e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function s(){c(),u(),d(),p(),g(),C(),l(),i()}function i(){var e="";switch(t.iconClass){case"toast-success":case"toast-info":e="polite";break;default:e="assertive"}I.attr("aria-live",e)}function a(){E.closeOnHover&&I.hover(H,D),!E.onclick&&E.tapToDismiss&&I.click(b),E.closeButton&&j&&j.click(function(e){e.stopPropagation?e.stopPropagation():void 0!==e.cancelBubble&&e.cancelBubble!==!0&&(e.cancelBubble=!0),E.onCloseClick&&E.onCloseClick(e),b(!0)}),E.onclick&&I.click(function(e){E.onclick(e),b()})}function r(){I.hide(),IE.showMethod,E.timeOut>0&&(k=setTimeout(b,E.timeOut),F.maxHideTime=parseFloat(E.timeOut),F.hideEta=(new Date).getTime()+F.maxHideTime,E.progressBar&&(F.intervalId=setInterval(x,10)))}function c(){t.iconClass&&I.addClass(E.toastClass).addClass(y)}function l(){E.newestOnTop?v.prepend(I):v.append(I)}function u(){if(t.title){var e=t.title;E.escapeHtml&&(e=o(t.title)),M.append(e).addClass(E.titleClass),I.append(M)}}function d(){if(t.message){var e=t.message;E.escapeHtml&&(e=o(t.message)),B.append(e).addClass(E.messageClass),I.append(B)}}function p(){E.closeButton&&(j.addClass(E.closeClass).attr("role","button"),I.prepend(j))}function g(){E.progressBar&&(q.addClass(E.progressClass),I.prepend(q))}function C(){E.rtl&&I.addClass("rtl")}function O(e,t){if(e.preventDuplicates){if(t.message===w)return!0;w=t.message}return!1}function b(t){var n=t&&E.closeMethod!==!1?E.closeMethod:E.hideMethod,o=t&&E.closeDuration!==!1?E.closeDuration:E.hideDuration,s=t&&E.closeEasing!==!1?E.closeEasing:E.hideEasing;if(!e(":focus",I).length||t)return clearTimeout(F.intervalId),I[n]({duration:o,easing:s,complete:function(){h(I),clearTimeout(k),E.onHidden&&"hidden"!==P.state&&E.onHidden(),P.state="hidden",P.endTime=new Date,f(P)}})}function D(){(E.timeOut>0||E.extendedTimeOut>0)&&(k=setTimeout(b,E.extendedTimeOut),F.maxHideTime=parseFloat(E.extendedTimeOut),F.hideEta=(new Date).getTime()+F.maxHideTime)}function H(){clearTimeout(k),F.hideEta=0,I.stop(!0,!0)E.showMethod}function x(){var e=(F.hideEta-(new Date).getTime())/F.maxHideTime*100;q.width(e+"%")}var E=m(),y=t.iconClass||E.iconClass;if("undefined"!=typeof t.optionsOverride&&(E=e.extend(E,t.optionsOverride),y=t.optionsOverride.iconClass||y),!O(E,t)){T++,v=n(E,!0);var k=null,I=e("
"),M=e("
"),B=e("
"),q=e("
"),j=e(E.closeHtml),F={intervalId:null,hideEta:null,maxHideTime:null},P={toastId:T,state:"visible",startTime:new Date,options:E,map:t};return s(),r(),a(),f(P),E.debug&&console&&console.log(P),I}}function m(){return e.extend({},p(),b.options)}function h(e){v||(v=n()),e.is(":visible")||(e.remove(),e=null,0===v.children().length&&(v.remove(),w=void 0))}var v,C,w,T=0,O={error:"error",info:"info",success:"success",warning:"warning"},b={clear:r,remove:c,error:t,getContainer:n,info:o,options:{},subscribe:s,success:i,version:"2.1.3",warning:a};return b}()}
https://requirejs.org/docs/errors.html#mismatch
at makeError (require.js:5:1795)
at T (require.js:5:8677)
at require.js:5:15068

I believe it has something to do with the require.js. I am currently using require.js version 2.3.6, bootstrap5 and jquery-3.6.1 in my code.
PS: I am no expert at front-end development

TOASTR_OPACITY has no effect

Hi,

When I set TOASTR_OPACITY = False in my app config the toastr remains having an opacity of 0.8. I can overwrite this with CSS but it seems the options does not have any effect.

Using single quotation marks in messages result in javascript errors, as the messages are not escaped

Suggest a function, wrapper or filter to escape single quotes in lines 71 and 73
This isn't a massive problem for quotes (double quotes don't have the same issue) but apostrophes break things.

toastr.info(\'{{ message }}\', \'{{ category|capitalize }}\')
{% else %}
toastr.{{ category }}(\'{{ message }}\', \'{{ category|capitalize }}\')

              toastr.info(\'{{ message | replace("'","\\\\'") }}\', \'{{ category|capitalize }}\');
            {% else %}
              toastr.{{ category }}(\'{{ message | replace("'","\\\\'") }}\', \'{{ category|capitalize }}\');

Formatting

Thank you for making this available.

Is there any way i can change the format of the toasts (text color, background color etc)?

it seems the default is white background with very light grey text. With the opacity and a white background behind the toast, it becomes impossible to see the content of the toast.

ReferenceError: Can't find variable: jQuery

I am having issues getting this to work.

This is currently present in my <head>:

<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.css" rel="stylesheet">
<script type="text/javascript">
      (function($) {
        $(document).ready(function() {
          toastr.options.closeButton = true;         toastr.options.timeOut = 15000;         toastr.options.extendedTimeOut = 1000;         toastr.options.positionClass = "toast-top-right";         toastr.options.preventDuplicates = false;         toastr.options.newestOnTop = false;         toastr.options.progressBar = true; 
          
            
              toastr.info('solly', 'Message')
            
          
        });
      })(jQuery);
    </script>

And just above my closing </body> tag:

<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>

The error I am getting in the console is:

ReferenceError: Can't find variable: jQuery

Which makes sense, as I don't want to include jquery in the head but just above the closing body tack for performance reasons

The icon resolution issue

Thanks to all these great works achieved by you guys, It's amazingly great and convenient!
However, the resolution of the messaging icon and font is not good as excepted,
It will be great if you guys can alternate the icon with a clear and modern svg icon which will not add explicit overhead,
or give the users a interface to change the icon and font, as well as obey the concise and powerful style of this software.
cheers!๐Ÿš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.