Implementing Web Push Notification using Flask

Asked

Viewed 81 times

1

I’m trying to create a way to implement a web push notification in my project. Using some tutorials I managed to generate an alert with the message I want.

#!/usr/bin/env python
from flask import Flask, render_template, request, session, Response
from redis import Redis
import datetime

app = Flask(__name__)
app.secret_key = 'asdf'
red = Redis(host='localhost', port=6379, db=0)

def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    for message in pubsub.listen():
        print message
        yield 'data: %s\n\n' % message['data']


@app.route('/post', methods=['POST','GET'])
def post():
 if request.method=="POST":
    message = request.form['message']
    now = datetime.datetime.now().replace(microsecond=0).time()
    red.publish('chat', u'[%s] %s: %s' % (now.isoformat(), 'Thiago', message))
 return render_template('post.html')


@app.route('/stream')
def stream():
    return Response(event_stream(),
                          mimetype="text/event-stream")

@app.route('/')
def index():
    return render_template('index.html')

if __name__=="__main__":
    app.run(host='0.0.0.0', port=8001, debug=True,threaded=True)

index.html

<html>
<head>
    <title>Test Page</title>
</head>
<body>
    <h1>Testing...</h1>
    <div id="target_div">Watch this space...</div>
</body>
<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
<script type="text/javascript">
    var source = new EventSource('/stream');
    source.onmessage = function (event) {
     alert(event.data);
    };
</script>
</html>

post html.

<html>
<head>
    <title>Posting a Message</title>
</head>
<body>
    <form action="{{url_for('post')}}" method='post'>
        Message: <input type="text" name="message" size='50'> <input type="submit" value="Launch!">
    </form>
</body>
</html>

Well, very simple, accessing the page /post, write a message and the user with the OPEN page, receives the message in the form of Alert.

What I would like to try to implement is that I don’t need to be open page, I believe I would have to use sub redis. And let the notification go up like a box in the lower right corner.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.