title: Flask: How to detect disconnection in infinite response generator?
body: <p>In <a href="http://flask.pocoo.org/docs/0.10/" rel="noreferrer">flask</a> I have a page that is used with <code>EventSource</code> to receive updates/events.</p>
  
  <p>It's implemented in fairly trivial manner:</p>
  
  <pre><code>@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")
  </code></pre>
  
  <p>Problem I am having is that each time I reload page that connect <code>EventSource</code> to my "update" page it creates a new thread to serve that "update" request. And it <strong>never dies</strong>. </p>
  
  <p>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.</p>
  
  <p>Simple solution I was hoping to get was to replace <code>while True</code> with some form of <code>while is_connected()</code>.</p>
  
  <p>However I can't seem to find a way to detect whether browser is still connected or not.</p>
  
  <p><strong>Question:</strong> How can I check inside my generator that connection is still alive?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Looking through code it seems that it should call <code>close()</code> on generator, so in theory it should throw <code>GeneratorExit</code> at some point in my <code>gen()</code>.</p>
  
  <p>However I don't see any trace of this happening and with each call I see <code>pstree</code> producing one more entry after each request/connection to <code>/updates</code>.</p>