[Python] Why does browser ignore html code when displaying server-sent events

Discussão em 'Python' iniciado por Stack, Março 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use SSE to automatically update an image source imbedded in the html on a web app I've created. Although I've used Python and Flask to create several pages in my app, I'm new to SSE, and I'm trying to make work an SSE example based on https://dev.to/philip_zhang_854092d...thon-and-go-for-real-time-data-streaming-38bf.

    The output does not appear as I would expect. Instead of getting an actual web page with the sentences appearing one by one, the browser shows the literal strings produced by the yield statement in the for-loop, complete with the substring "data:" and the double line feeds. I used 127.0.0.1/events as the URL. (See below.)

    [​IMG]

    I placed the Python code in a file called "SSE_tester.py" (see below). Here is the code from that web page:

    from flask import Flask, Response

    app = Flask(__name__)


    @app.route('/events')
    def sse_handler():
    def generate():
    paragraph = [
    "Hello, this is an example of a continuous text output.",
    "It contains multiple sentences, each of which will be sent to the client as an event.",
    "This is to simulate the functionality of Server-Sent Events (SSE).",
    "We can use this method to push real-time updates.",
    "End of sample text, thank you!",
    ]

    for sentence in paragraph:
    yield f"data: {sentence}\n\n"

    import time
    time.sleep(1)

    return Response(generate(), mimetype='text/event-stream')


    if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8081, debug=True)


    I don't see anything in the code above which tells the script where to find the browser API (except maybe app.route?). I am a total newbie when it comes to Javascript and I would not be surprised if there's some magic thing I'm supposed to do with JS that the author of this code assumes the reader knows and I don't. If that is the case, help on that would be much appreciated.

    The example also contained code for the browser API, which I will repeat below:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example </title>
    </head>
    <body>
    <h1>Server-Sent Events Example </h1>
    <div id="messages"></div>
    <script>
    window.onload = function() {
    if (typeof(EventSource) !== "undefined") {
    const eventSource = new EventSource('/events');

    eventSource.onmessage = function(event) {
    const newElement = document.createElement("p");
    newElement.textContent = "Message: " + event.data;

    document.getElementById("messages").appendChild(newElement);
    };

    eventSource.onerror = function(event) {
    console.error("Error occurred: ", event);
    const newElement = document.createElement("p");
    newElement.textContent = "An error occurred while connecting to the event source.";
    document.getElementById("messages").appendChild(newElement);
    eventSource.close();
    };
    } else {
    document.getElementById("messages").textContent = "Sorry, your browser does not support server-sent events...";
    }
    };
    </script>
    </body>
    </html>


    It looks to me like this API has html code in it, so I placed it in a file 'events.html', which I placed in a subdirectory called 'events', based on app.route.

    If I interpret the html in the browser API correctly, there should be, at a minimum, a header labeled "Server-Sent Events Example", but there isn't. To prove to myself the html file is not making any difference, I deleted it temporarily. Same results; it is apparently being ignored.

    [​IMG]

    I tried changing html file name to 'index.html' and that didn't help either.

    I'm not getting any error messages.

    So what do I need to do differently? Why is the browser and/or Python script ignoring the Browser API? I figure if I can't get this example to work, I probably will not able to get SSE to work in my app, either.

    BTW, my organization's IT department runs a pure Windows shop, so proposed solutions requiring Linux will probably not be helpful. Browser is Chrome Version 134.0.6998.36 running on Windows 10 Enterprise. Python 3.9.13 running in Wing Pro IDE. Flask version 1.1.2.

    At first blush this may appear to be the issue described in Flask app keeps displaying raw HTML code, but not the actual rendering, but this issue was caused by "random tags" generated by ChatGPT, and the code I'm testing does not appear to have any random tags and was (presumably) created by a human. Furthermore, I have successfully created several web pages using Flask, and they are being rendered correctly.

    I might also mention that I only need one-way communication, so web socket would probably be overkill for my situation.

    Thank you very much in advance to those who respond to this post.

    Continue reading...

Compartilhe esta Página