0

In flask I have a page that is used with EventSource to receive updates/events.
It’s implemented in fairly trivial manner:
@route(‘/updates’)
def updates():
def gen():
while True:
update = make_update()
yield “data: {0}\n\n”.format(json.dumps(update))
return Response(stream_with_context(gen()), mimetype=”text/event-stream”)

Problem I am having is that each time I reload page that connect EventSource to my “update” page it creates a new thread to serve that “update” request. And it never dies.
There are updates coming through, so it means it is pushing data somewhere making my server use more and more threads, and more and more memory.
Simple solution I was hoping to get was to replace while True with some form of while is_connected().
However I can’t seem to find a way to detect whether browser is still connected or not.
Question: How can I check inside my generator that connection is still alive?
EDIT
Looking through code it seems that it should call close() on generator, so in theory it should throw GeneratorExit at some point in my gen().
However I don’t see any trace of this happening and with each call I see pstree producing one more entry after each request/connection to /updates.

Kuldeep Baberwal Changed status to publish February 17, 2025