How to know when client disconnects in Flask app

Viewed 1167

I'm trying to use HTTP long polling, roughly something like this:

@app.route('/get_stuff', methods=["GET"])
def get_stuff():
    while True:
        stuff = database.lookupSomething()
        if stuff:
            return json.dumps(stuff)
        else:
            time.sleep(1)

This works excellent however if the client cuts the connection, the server will still run the loop. I would like to replace the loop with something like this:

while client.is_connected():
    ....

However, I cannot find any way of knowing if the connection is still valid. Others have asked the same question, and the answer has been to use SocketIO. I cannot do this however and would rather use a simple GET request like above. Is there a way of knowing if the client has closed his connection?

0 Answers
Related