首页 > 解决方案 > 如何使用 Flask 创建 Web 推送通知

问题描述

我正在尝试在我的项目中实现网络推送通知。使用一些教程,当我发布消息时,我在索引页面上创建了一个警报。但这远不是我想要的。

索引.html

<html>
<head>
    <title>Test Page</title>
</head>
<body>
    <h1>Testing...</h1>
</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>

应用程序.py

#!/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('notification')
    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('notification', u'[%s] %s: %s' % (now.isoformat(), 'Aviso', 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)

好吧,我想实现一个订阅系统,我想是这样调用的。用户允许从网站接收通知,当他点击“新闻”时,它会打开一个包含详细内容的新页面。

接收消息不需要打开索引页面。

标签: pythonflaskredispush-notification

解决方案


推荐阅读