How to know when client disconnects in Flask app
Asked Answered
A

0

7

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?

Aikoail answered 22/11, 2017 at 18:48 Comment(5)
Using the definitions in RFC6202, your code implements "HTTP Streaming", not "HTTP Long Polling".Reptile
Streaming: "The HTTP streaming mechanism keeps a request open indefinitely. It never terminates the request or closes the connection, even after the server pushes data to the client."Aikoail
Long polling: "The server achieves these efficiencies by responding to a request only when a particular event, status, or timeout has occurred.".Aikoail
I don't keep the connection indefinitely, streaming objects continuously. I send one response but not until the object is there to be sent. Thus, long polling.Aikoail
You are right, I am wrong. I was confused by your while True loop. I missed the "return", and thought you were sending back a series of JSON documents, not just one.Reptile

© 2022 - 2024 — McMap. All rights reserved.