我一直在开发flask应用程序,并在其中尝试实现SSE。检查下面的代码:
index.py
@app.route('/stream', methods=['GET'])
@cross_origin()
def stream():
def listenstream():
print("listening")
displaytext = { 'requestdata': 'Sampledata', 'responsedata' : 'Sample Data'}
displaytext=json.dumps(displaytext)
yield 'event: message\n'
yield 'data : '+displaytext+'\n\n'
time.sleep(1.5)
return Response(response=listenstream(),status=200,mimetype="text/plain",content_type='text/event-stream')
custom.js
var eventSource = new EventSource("/stream");
eventSource.onmessage = function (e) {
console.log("Onmessage"+e)
}
eventSource.onerror = function (e) {
console.log("Onerror"+JSON.stringify(e))
}
eventSource.onopen = function (e) {
console.log("Onopen"+JSON.stringify(e))
}
此处eventSource.onerror => {“ isTrusted”:true},eventSource.onopen => {“ isTrusted”:true},但未调用eventSource.onmessage。我在js文件中尝试过addEventListener:
var eventSource = new EventSource("/stream");
eventSource.addEventListener('message', (e) => {
console.log("Received update")
})
如果我渲染链接'http://localhost:5000/stream',它将给出:
事件:消息
数据:{“ requestdata”:“ Sampledata”,“ responsedata”:“ Sampledata”}
但是我需要链接'http://localhost:5000'上的数据。这是正确的做法吗?
将不胜感激:)
更新后为我解决了这个问题:
index.py
yield "event: {0}\ndata: {1}\n\n".format("listen",displaytext)
return Response(listenstream(), mimetype="text/event-stream")
custom.js
var eventSource = new EventSource("/stream");
eventSource.addEventListener('listen', function(e){
//Code here
},false);