以下服务有json数据。该数据是从mongodb获取的。
@app.route('/notifications',methods = ['GET', 'POST'])
def notifications():
detailes = Notifications.objects()
dt=[]
for i in detailes:
data={}
data['usertype'] = i.usertype
data['user_id'] = i.user_id
data['date_time'] = i.date_time
data['message'] = i.message
data['title'] = i.title
data['status'] = i.status
data['last_notification_time'] = i.last_notification_time
json_data = json.dumps(data)
test=json.loads(json_data)
dt.append(test)
return jsonify(dt)
现在我需要将这个最终的json数据发送到另一个服务器和另一个app.py中的另一个服务。下面是我的代码。
from flask import Flask, render_template,request
from flask_sse import sse
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.register_blueprint(sse, url_prefix='/stream')
@app.route('/')
def index():
return render_template("index.html")
@app.route('/hello')
def publish_hello():
sse.publish({"message": "Hello!"}, type='greeting')
return "Message sent!"
我需要在消息[sse.publish({“message”:“Hello!”},type ='greeting')]的位置传递变量“dt”中的json_data,这是在hello服务中。
答案 0 :(得分:0)
将dt注入传递给客户端的字典。
def some_function_that_grabs_messages():
return some_data
@app.route('/hello')
def publish_hello():
dt - some_function_that_grabs_messages():
sse.publish({"message": dt}, type='greeting')
return "Message sent!"
<强>更新强>
sse.py
from flask import Flask, render_template
from flask_sse import sse
import pymysql as mysql
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.register_blueprint(sse, url_prefix='/stream')
def conn_handler():
conn = mysql.connect(host='localhost', user='root', password='123456', database='feedparser', charset='utf8mb4')
cur = conn.cursor()
cur.execute("SELECT title FROM articles WHERE id < 30")
data = cur.fetchall()
conn.close()
return data
@app.route('/')
def index():
return render_template("index.html")
@app.route('/hello')
def publish_hello():
data = conn_handler()
for title in data:
sse.publish({"message": title[0]}, type='greeting')
return "Message sent!"
模板/ index.html中
<!DOCTYPE html>
<html>
<head>
<title>Flask-SSE Quickstart</title>
</head>
<body>
<h1>Flask-SSE Quickstart</h1>
<script>
var source = new EventSource("{{ url_for('sse.stream') }}");
source.addEventListener('greeting', function(event) {
var data = JSON.parse(event.data);
document.getElementById("messages").innerHTML += data.message+"<br />";
}, false);
source.addEventListener('error', function(event) {
alert("Failed to connect to event stream. Is Redis running?");
}, false);
</script>
</body>
<div id="messages">
</div>
</html>
运行
$ gunicorn sse:app --worker-class gevent --bind localhost:8000