title: Python Flask, how to detect a SSE client disconnect from front end Javascript
body: <p>Maybe this is a problem in Flask, there is no way to handle disconnection event on the server side.</p>
  
  <p>In Response class, there is a method named "call_on_close", where we can add a function without argument, e.g. on_close(), it will be fired when the response object's close method called, but this doesn't happen when I call EventSource.close() from the client side in Javascript.</p>
  
  <p>code on server side:</p>
  
  <pre><code>from flask import Response
  r = Response(stream(), ...)
  r.call_on_close(on_close)
  return r 
  
  def on_close():
    print "response is closed!"
  
  def stream():
    ...  # subscribe to redis
    for message in pubsub.listen():
      ....
      yield 'data: %s\n\n' % message
  </code></pre>
  
  <p>on client side: add unload handler to page with SSE</p>
  
  <pre><code>$(window).unload(
    function() {
      sse.close();
    }
  }
  </code></pre>
  
  <p>Anything is wrong?</p>
  
  <p>Any suggestions or solution with code is appreciated!</p>
  
  <p>Thanks in advance!</p>