I have been developing a flask application and where trying to implement SSE. Check my code below:
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))
}
Here eventSource.onerror => {"isTrusted":true} ,eventSource.onopen => {"isTrusted":true} but eventSource.onmessage is not being invoked. I tried addEventListener in js file:
var eventSource = new EventSource("/stream");
eventSource.addEventListener('message', (e) => {
console.log("Received update")
})
If I render to the link 'http://localhost:5000/stream', it gives :
event: message
data : {"requestdata": "Sampledata", "responsedata": "Sampledata"}
But I need the data on the link 'http://localhost:5000'. Is this the correct way of doing it?
Help will be appreciated :)
Following updation resolved the issue for me :
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);