python - 如何使用 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)
好吧,我想实现一个订阅系统,我想是这样调用的。用户允许从网站接收通知,当他点击“新闻”时,它会打开一个包含详细内容的新页面。
接收消息不需要打开索引页面。
解决方案
推荐阅读
- c# - 根据路径使用 OAuth 和 ADFS 进行 ASP.Net 身份验证
- asp.net-mvc - 从 CMS.File 页面类型中检索二进制数据
- python-3.x - 通过另一种方法退出 lambda 表达式
- excel - Power Query - 规范化列
- java - 无法在 1.7 java for AIX 中找到 KeyTool 类
- python - 在带有 Jinja2 的 appengine 中使用图表
- python - 在 Django python 表单中,我如何给表单字段一个“第二个名字”?
- node.js - 获取 node.js 中特定密码的 IV 大小
- python - 如何在不使用 gmpy 的情况下获得 64 位整数?
- powerbi - 如何使用快速测量 MoM% 并在视觉上应用过滤器以排除当前月份