1

I am trying to figure out how to send a constant stream of data in Flask and then read it in JavaScript.

This example is very basic because I am just trying to get it working.

Flask route:

@app.route("/gen", methods=["GET"])
def gen():
    def make():
        while True:
            yield "Hello"
            time.sleep(1)
    return Response(make())

JavaScript:

<script>
    const url = 'http://10.0.1.11:8001/gen';

    fetch(url)
        .then(function (response) {
            return response;
        })
        .then(function (data) {

            console.log(data)

        })
</script>

This prints to the console log only one time and I do not see the message "Hello". What I would like to see is "Hello" printed every second. My end goal is to send json from my generator and parse it in my html document.

Thanks, Chris

Chris
  • 985
  • 2
  • 7
  • 17
  • 1. you need to change `return response;` to `return response.text();` 2. remove the time command and instead use [`setInterval(..., 1000)`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) in your client-side JS –  Jun 01 '22 at 20:48
  • Hello. I already know how to use setInterval but I thought using a stream would be the more proper way? This way there is only 1 request to flask instead of spamming the logs. – Chris Jun 01 '22 at 20:56
  • I've never done that but you can check here: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams (or use socket.io instead) –  Jun 01 '22 at 20:59

0 Answers0