How do I run Server Send Events async with flask?

I´m using Server Send Events with Python and Flask so that the Server can send thinks to the webclient and the webclient does not have to send 10 requests per second. My code worked just fine without async when I only want to connect one device to the SSE stream. If I try to connect another devie it trys to load for infinity because the server is stuck in the while true loop.


This is the woking code for one device:

from flask import Flask, Response
from gevent.pywsgi import WSGIServer


app = Flask(__name__)

@app.route("/")
def index():
    return open("index.html").read()

@app.route(f"/listen")
def listen():
    def eventStream():
        while True:
            yield "data: {}\n\n".format(get_stream_data())
    return Response(eventStream(), mimetype="text/event-stream")

def get_stream_data():
    return "data"
        

if __name__ == "__main__":
    http_server = WSGIServer(("0.0.0.0", 5000), app)
    http_server.serve_forever() 

This is my attempt to solve the Problem:

from flask import Flask, Response
from gevent.pywsgi import WSGIServer
import asyncio
import time


app = Flask(__name__)

@app.route("/")
def index():
    return open("index.html").read()

@app.route(f"/listen")
async def listen():
    async def eventStream():
        while True:
            yield "data: {}\n\n".format(get_stream_data())
    return Response(await eventStream(), mimetype="text/event-stream")

def get_stream_data():
    return "data"
        

if __name__ == "__main__":
    http_server = WSGIServer(("0.0.0.0", 5000), app)
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(http_server.serve_forever())

This is the HTML from index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client</title>
</head>
<body>
    <script>
        var eventSource = new EventSource(`/listen`)
            eventSource.onmessage = function(e) {
                console.log(e)
        };
    </script>
</body>
</html>
🔴 No definitive solution yet