如何使用Flas创建web推送通知

2024-04-20 00:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在我的项目中实现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>

在帖子.html在

^{pr2}$

在应用程序副本在

#!/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)

好吧,我想实现一个订阅系统,我想这就是所谓的。用户允许接收来自网站的通知,当他点击“新闻”时,会打开一个新页面,其中包含详细内容。在

接收邮件时不需要打开索引页。在


Tags: importeventappmessagedatastreamdatetimerequest